0

I am pasting a snippet from mozilla docs.

An arrow function does not create its own this, the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}
var p = new Person();

My confusion is when the above code is executed, the setInterval function will be replaced by its implementation with the anonymous function passed as argument like this.

setinterval(){

-------some code for repeating the function passed as argument

the function itself



  () => {
 this.age++;   //line 00
    }
    -----
    some code 

    }

line 00 : here this will not point to anonymous function as arrow function is used and will point to the enclosing execution context. for what i understood the enclosing execution context here is setInterval function but for that no age property is defined. I know I am wrong as age points to person object as it is running fine.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Mozif Beigh
  • 109
  • 1
  • 1
  • 7
  • Possible duplicate of [When should I use Arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6) – Erazihel Sep 06 '17 at 13:28

1 Answers1

4

Where was the function created, not where it was called, that is it's enclosing context. Your function is created in the function Person, so this function is the enclosing context for the arrow function.

You only create an arrow function and pass it to the setInterval, it is not created in the setInterval's definition. This

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++;
  }, 1000);
}

is equivalent to this. Here you see that func's enclosing context is the Person.

function Person(){
   this.age = 0;

   var func = () => {
       this.age++;
   };

   setInterval(func, 1000);
}
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101