Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 arrow function and this context [duplicate]

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?

like image 294
Shane Avatar asked Feb 20 '26 13:02

Shane


1 Answers

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.

like image 167
Frxstrem Avatar answered Feb 23 '26 03:02

Frxstrem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!