The this
keyword, again!
Be careful when you use this
in nested functions!
class MyClass { constructor() { this.value = 10; } myMethod1() { return function () { console.log(this); }; } myMethod2() { return () => { console.log(this); }; } } const obj = new MyClass(); obj.myMethod1()(); obj.myMethod2()();
In myMethod1
, we return a function with its own execution context, separate from that of myMethod
. Therefore, the "this" keyword on line 8 is not bound to MyClass
. On the other hand, we return an arrow function in myMethod2
. An arrow function does not have its own bindings to this
. Instead, it inherits the execution context of myMethod2
. Therefore, the "this" keyword on line 14 refers to MyClass
.