0
var cat = {
lives: 9,
jumps: () => {
console.log(this.lives)
 }
}

I have heard that 'this' keyword in arrow function will point to the parent scope, so I have tried putting a variable with lives=9 in global object in node and this doesn't seems to work, am I missing something?

var lives=9
var cat = {
lives: 9,
jumps: () => {
console.log(this.lives)
 }
}
  • 1
    Your second piece of code should work *as long as* it's in the global scope. Otherwise variables will not be attached to `this`. In global scope `this` will be the global object. – VLAZ Jul 06 '21 at 13:10
  • Define `this doesn't seems to work`? – Jeremy Thille Jul 06 '21 at 13:11

1 Answers1

5

Arrow functions have a lexical this which means that the value of this inside the function is the same as the value of this outside the function.

It does not mean that this points to an object containing all the variables from outside the function.

const anObject = {
  aValue: "example value",
  aMethod: function() {
    console.log("aMethod", this.aValue);

    const arrow = () => {
      console.log("arrow", this.aValue);
    }
    
    arrow();
  }
}

anObject.aMethod();

const copyOfAMethod = anObject.aMethod;
copyOfAMethod();

Because aMethod is called as a method on anObject, the value of this inside aMethod is anObject.

Because arrow is declared inside aMethod, the value of this is the same as it is for aMethod.

If the function is copied elsewhere so it has a different this value, then the arrow function created when the copy is called it will have the same different value.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335