1

I know arrow functions do not have their own "this", the borrow the "this" of their enclosing lexical scope.

const person = {
    points: 23,
    score: () => {
      this.points++;
  }
};

Why does the person.score give me undefined, as an arrow function, it should have access to this?

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
  • In this example, the `this` gets the global scope which is equal to the `window` object it the `person` object not within any other scoped block. If you want to get the `person` object's reference then you have to write `score: function() {}`. – Sajeeb Ahamed Jul 10 '20 at 20:03
  • Because it is a function and not returning anything. – xMayank Jul 10 '20 at 20:03

1 Answers1

1

Arrow function do not have their own this function. Because the arrow function doesn't have a this associated with it, it uses the parent's this.

In your example, this inside person will point to parent and the parent of the person object is Window. So, the this points to enclosing scope and not the person object. In your case , this is bound to global object. You can see the contents of this printed below (the Window object).

const person1 = {
  points: 23,
  score: function(){
    console.log(this);
  }
};
// this in score function will point to person1
person1.score();

const person2 = {
  points: 23,
  score: () => {
    console.log(this);
  }
};
// here, this will point to global object       
person2.score();
phhu
  • 1,462
  • 13
  • 33
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32