I have read some topics on arrow function, but below code just confuses me.
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
first : () => {
console.log(this) //does not refer to bunny
},
second: function(){
console.log(this) //refers to bunny
},
third() {
this.tasks.forEach((task) => {
console.log(this); //refers to bunny
});
}
};
bunny.first();
bunny.second();
bunny.third();
Can anyone tell me how come third function inner function this refers to current object, while the first one does not. Is it not when we use arrow function, this refers to current scope where it is defined?
Arrow functions are more or less equivalent to function statements, except that they bind the this argument to that of the parent scope.
In other words, if an arrow function appears in the top scope, its this argument will always refer to the global scope (e.g., window in browsers or global in node.js), while an arrow function inside a regular function will have its this argument the same as its outer function, as your code demostrates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With