1
const md = {
  methodOne: () => {
    console.log(this.anotherMethod())
  },
  anotherMethod: () => 'anotherMethod'
}

When I do md.methodOne() I got anotherMethod is undefined error. How do I call anotherMethod in methodOne?

alice tang
  • 23
  • 3
  • Arrow functions do not set `this`, so `this.anotherMethod` cannot be resolved. If you define `methodOne` with a `function` declaration, the code will work. – Pointy Nov 16 '18 at 14:26
  • 2
    makes no sense to `console.log(this.anotherMethod())` since anotherMethod does not return anything – epascarello Nov 16 '18 at 14:26
  • @epascarello edited my question, how about now? this is `gone` if I use arrow function, right? – alice tang Nov 16 '18 at 14:53

1 Answers1

0

The problem is in your arrow functions. An arrow function does not have its own this; the this value of the enclosing lexical context is used i.e. Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope . Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the lexically enclosing function:

Also, you don't need to type return when you have :

() => return 'some message'

The arrow function will return implicitly the value or the result of an expression:

const msg =  () => 'some message'

const result = () => 5 * 5; //25

Just for the sake of it, this is how it should look:

const md = {
  methodOne:function () {
    console.log(this.anotherMethod());
  },
  anotherMethod: function (){
    return 'anotherMethod';
  }
}

console.log(md.methodOne());
squeekyDave
  • 832
  • 13
  • 31