3

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?

Shane
  • 5,517
  • 15
  • 49
  • 79
  • arrow functions don't define a `this` in their own lexical scope, so it gets it from its outer scope, just like it would get a normal variable not defined within itself. –  Sep 27 '16 at 22:48
  • The current `this` context inside property expressions of an object literal is not the constructed object. – Bergi Sep 27 '16 at 22:59
  • See [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Sep 28 '16 at 00:29

1 Answers1

4

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.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • Isn't the outer fn forEach? And the value of `this` attached to it isn't `this.tasks`? Can anyone give a more step-by-step explanation? – Irina Jan 10 '23 at 21:05