0
const objectLiteral = {
  x: 5,
  getX: () => {
      console.log(`The value of x is ${this.x}`); 
  }
} 
x.getX(); // The value of x is undefined

Why this doesn't bind to the getX method when I use an object literal? Doesn't the arrow function get their this from the parent scope? In this case the objectLiteral. But it does when I use class generated object.

class classObject {
  x = 5;
  getX = () => {
      console.log(`The value of x is ${this.x}`);
  }

  const classObjectInstance = new classObject();
  classObjectInstance.getX(); // The value of x is 5
}
ordancheg
  • 43
  • 5
  • Class fields are syntactic sugar for setting a property in the constructor, i.e. `constructor() { this.getX = () => ...; }`, where `this` refers to the new instance. That's not the case of object literals. The property values are evaluated before the object even exists. – Felix Kling Nov 15 '21 at 17:10
  • Oh ok, thank you – ordancheg Nov 15 '21 at 17:20

0 Answers0