0

MDN: "In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object"

If we have an object:

const object = {
  arrowFunc: () => this,
};

and then we call:

console.log(object.arrowFunc()); // Window {window: Window, self: Window, document: document, name: '', location: Location, …}

We get the window object, why is the arrow function not returning the object itself as this?

If the arrow function retains the this value of the enclosing lexical scope, then shouldn't that be the object where function itself is defined i.e object?

Elbasel
  • 11
  • 4
  • 3
    *If the arrow function retains the this value of the enclosing lexical scope, then isn't that the object itself where it's defined?* — No. It is the `this` value of the **function** where it is defined (or `window` if it is outside of any function). Object literals don't create a new lexical scope. – Quentin Jul 25 '22 at 10:02
  • Can you please tell me why then if I instead use a regular function inside an object literal like `const object = {logThis() {console.log(this)}}}` it logs `object`? – Elbasel Jul 25 '22 at 10:24
  • That's the primary difference between arrow and other functions. https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work-and-when-should-it-be-used – Quentin Jul 25 '22 at 10:25

0 Answers0