0

I am using several fat arrow functions in a javascript class but my this keeps having a null value. This is for a reactjs application using sagas. From prior readings, etc. I was under the assumption that fat arrow functions got their scope from the parent they were contained in. However, that is not what is happening here.

Here is an example illustrating the issue I am having:

export default class Base {
    constructor() {
    this.autos = [];
    }
}

export default class Auto extends Base {
    createAuto = (auto) => {
        debugger;
        this.autos.push(auto); /This line is where this = null
        return this.autos;
    }
}

……

function* createAuto(auto) {
  try {
    let a = new Auto();
    …..
    let result = yield(a.createAuto, auto);
  } catch (e) {
    console.log(e);
  }
}

When createAuto method is called, this is null. How could this be the case if createAuto is contained within the Auto class? I would think this would be the one for Auto.

user1790300
  • 2,143
  • 10
  • 54
  • 123
  • That's expected. Arrow functions bind the value of `this` when they're created. – Barmar Apr 24 '19 at 16:20
  • You generally shouldn't use arrow functions for class methods. – Barmar Apr 24 '19 at 16:21
  • @Barmar I am not sure I understand what you mean? If the outer container is a class, wouldn't that mean it will reference the this for the class? – user1790300 Apr 24 '19 at 17:43
  • There's no such thing as "this for the class". At the top-level of a class definition, there's no `this` binding, it only exists when you call a method through an object, e.g. `foo.createAuto()`. But arrow functions don't get get `this` this way. – Barmar Apr 24 '19 at 18:41
  • Change it to `function createAuto(auto)` and it will work as you expect. – Barmar Apr 24 '19 at 18:43
  • The confusion is that I initially thought that the fat arrow solved the issue of needing to bind. – user1790300 Apr 25 '19 at 14:07

0 Answers0