1

Consider this javascript:

let m = {
  add: (a,b) => a+b,
  subtract: (a,b) => a-b,
  doit: () => console.log(this.add(5,4)),
};

m.doit();

When I run this code, I get the following error:

  doit: () => console.log(this.add(5,4)),
                               ^
TypeError: this.add is not a function

What is the proper way to call the add function from within doit?

dcp
  • 54,410
  • 22
  • 144
  • 164
  • 1
    **Arrow function** don't bind `this`. A regular function: `doit: function () { console.log(this.add(5,4)); }` should work. – ibrahim mahrir Jul 18 '17 at 00:23
  • 1
    the this argument inside of arrow functions is bound to the this of the enclosing type. In the above code you could ether replace your functions with full "function" functions. Or you could reference "m" instead of "this" – Thomas Devries Jul 18 '17 at 00:25
  • 1
    Another way of solving the problem would be to use `m` instead of `this`: `doit: () => console.log( m.add(5,4) )` – ibrahim mahrir Jul 18 '17 at 00:26

2 Answers2

1

Arrow functions use this from outer scope but not the object they are called with.

Try this:

let m = {
  add: function(a,b) { return a+b; },
  doit: function() { console.log(this.add(5,4)); }
};

Yet, why not to use classes in this case?

c-smile
  • 26,734
  • 7
  • 59
  • 86
1

Arrow function allows to use lexical this, which is not m object but a context where m was defined.

The proper short syntax for object literal method is:

let m = {
  add: (a,b) => a+b,
  subtract: (a,b) => a-b,
  doit() {
    console.log(this.add(5,4));
  }
};
Estus Flask
  • 206,104
  • 70
  • 425
  • 565