这个问题在这里已有答案:
有三个文件。
context.js
导出传递给bind
的对象:module.exports = {
exceptionValue: 99
};
strategy.js
即导出我要调用的函数bind:module.exports = events => {
if (this.exceptionValue !== 99) {
throw new Error(this);
}
return events;
};
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
引用不起作用,它总是抛出异常。我根本无法访问我的上下文对象。我究竟做错了什么?为什么不工作?
你错误地认定了这个问题。出口无关紧要。
箭头函数已绑定this
值,您无法使用bind()
覆盖它。
使用函数表达式而不是箭头函数。
module.exports = function (events) {
if (this.exceptionValue !== 99) {
throw new Error(this);
}
return events;
};