0

I referred the documentation Arrow functions do not default this to the window scope, rather they execute in the scope they are created: What does this line mean? At some blogs I read they are defaulted the scope of nearest function or lexical scope. Can someone please elaborate? This is example from the developer.mozilla.org.

window.age = 10; // <-- notice me?
function Person() {
  this.age = 42; // <-- notice me?
  setTimeout(() => { // <-- Arrow function executing in the "p" (an instance of Person) scope
    console.log("this.age", this.age); // yields "42" because the function executes on the Person scope
  }, 100);
}

var p = new Person();
shukla yogesh
  • 167
  • 1
  • 9
  • `this` inside an arrow function resolves lexically, just like any other variable. As with any other variable you traverse the scopes up until you reach one that provides a `this` binding. A function declaration, as in the provided example, provides a `this` binding. – Felix Kling Dec 29 '20 at 14:03
  • 3
    Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – pilchard Dec 29 '20 at 14:04
  • @FelixKling Can we say that "this" is from enclosing scope? Or it has parent this which is enclosing lexical scope? – shukla yogesh Dec 29 '20 at 14:23
  • Yes, enclosing scope works. But it might not be the "next" enclosing scope (consider nested arrow functions). – Felix Kling Dec 29 '20 at 15:00
  • 2
    The sentence in MDN is pointless. [I've reported an issue](https://github.com/mdn/content/issues/733). – Bergi Dec 29 '20 at 15:30

0 Answers0