JavaScript`bind`不能处理导入的函数/对象[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

有三个文件。

  1. context.js导出传递给bind的对象:
module.exports = {
    exceptionValue: 99
};
  1. strategy.js即导出我要调用的函数bind:
module.exports = events => {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
  1. index.js导入以前的两个文件:
const context = require('./context');
const strategy = require('./strategy');

const strategyWithContext = strategy.bind(context);
return strategyWithContext(events);

events是传递给index.js的JSON对象列表。更准确地说,我从index.js导出这个函数,而调用它的人将提供这些事件。但它没什么特别的,只是一个JSON对象列表。

问题是策略函数中的this引用不起作用,它总是抛出异常。我根本无法访问我的上下文对象。我究竟做错了什么?为什么不工作?

javascript ecmascript-6 bind
1个回答
3
投票

你错误地认定了这个问题。出口无关紧要。

箭头函数已绑定this值,您无法使用bind()覆盖它。

使用函数表达式而不是箭头函数。

module.exports = function (events) {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
© www.soinside.com 2019 - 2024. All rights reserved.