0

I want to separate class methods into their own files. For example if I have a simple class like this in test.js:

export default class TestClass {

    testFunction(...args) {
        return require('./test-function').apply(this, args);
    }

}

And then in test-function.js method:

export default function() {
    /* `this` keyword works fine */
}

However, if I change it to an arrow function, then this does not work anymore (because of lexical scoping?):

export default () => {
    /* `this` doesn't work anymore */
}

How would I bind this properly so my arrow test function can use it?

John Derring
  • 515
  • 1
  • 4
  • 15
  • Please see [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) as well. – Felix Kling Mar 21 '16 at 02:11

1 Answers1

2

tl;dr - you cannot.

If you export an arrow function, that function will have it's lexical this bound to either the global object (non-strict mode) or it will be undefined (strict mode).

That's how arrow functions are supposed to work. If you need the function to get your class object's this, you must use standard function () {} body.

Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73