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
  • 51,027
  • 19
  • 136
  • 157

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
  • 24,546
  • 7
  • 54
  • 79
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
  • 150,909
  • 47
  • 291
  • 441