Arrow function and `this`

泪湿孤枕 提交于 2019-12-02 16:50:27

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/46076351/arrow-function-and-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!