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

时间:2019-04-16 16:08:28

标签: javascript ecmascript-6 bind

有三个文件。

  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引用无法正常工作,并且始终会引发异常。我根本无法访问上下文对象。我究竟做错了什么?为什么不起作用?

1 个答案:

答案 0 :(得分:3)

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

箭头功能已经绑定了一个bind()值,并且您不能使用module.exports = function (events) { if (this.exceptionValue !== 99) { throw new Error(this); } return events; }; 覆盖它。

使用函数表达式代替箭头函数。

dataset = pd.read_csv('c:/1/housing.data', engine = 'python', sep='\s+', header=None)
相关问题