Arrow functions, things are special/different. Arrow Functions always lexically bind the context (Lexical Scoping means that it uses this from the code that contains the Arrow Function.) and therefore this will refer to the originating context, ie the class.
A simpler example might make it more clear.
const obj = {
myVar: 'foo',
myFunc: function() {
console.log('Actual Variable value: ',this.myVar)
setTimeout(() => {
console.log('Set timeout using Arrow function: ',this.myVar)
}, 1000);
setTimeout(function () {
console.log('Set timeout using Normal function: ',this.myVar)
}, 1000);
}
}
obj.myFunc();
Output
Actual Variable value: foo
Set timeout using Arrow function: foo
Set timeout using Normal function: undefined
No comments:
Post a Comment