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
?
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
?
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());