2

There are three files.

  1. context.js which exports an object passed to bind:
module.exports = {
    exceptionValue: 99
};
  1. strategy.js that is exports the function I want to call bind on:
module.exports = events => {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
  1. index.js which imports both the previous files:
const context = require('./context');
const strategy = require('./strategy');

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

events is a list of JSON objects that are passed to index.js. To be more precise, I'm exporting this function from index.js and people who call it will provide those events. But it's nothing special, just a list of JSON objects.

The problem is that the this reference inside the strategy function isn't working and it's always throwing an exception. I can't access my context object at all. What am I doing wrong? Why isn't it working?

Benyamin Noori
  • 860
  • 1
  • 8
  • 24

1 Answers1

6

You've misidentified the problem. The export is irrelevant.

Arrow functions already bind a this value, and you can't override it with bind().

Use a function expression instead of an arrow function.

module.exports = function (events) {
    if (this.exceptionValue !== 99) {
        throw new Error(this);
    }
    return events;
};
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335