JavaScript`bind`在导入的函数/对象上不起作用

Ben*_*ori 1 javascript bind ecmascript-6

有三个文件。

  1. context.js将导出的对象导出到bind
module.exports = {
    exceptionValue: 99
};
Run Code Online (Sandbox Code Playgroud)
  1. strategy.js 那就是导出我想调用绑定的函数:
module.exports = events => {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
Run Code Online (Sandbox Code Playgroud)
  1. index.js 导入两个先前的文件:
const context = require('./context');
const strategy = require('./strategy');

const strategyWithContext = strategy.bind(context);
return strategyWithContext(events);
Run Code Online (Sandbox Code Playgroud)

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

问题在于,this策略函数内部的引用不起作用,并且始终会引发异常。我根本无法访问上下文对象。我究竟做错了什么?为什么不起作用?

Que*_*tin 5

您误解了问题。出口无关紧要。

箭头函数已经绑定了一个this值,您不能使用来覆盖它bind()

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

module.exports = function (events) {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
Run Code Online (Sandbox Code Playgroud)