简体   繁体   English

箭头功能和`this`

[英]Arrow function and `this`

I am pasting a snippet from mozilla docs. 我正在粘贴来自mozilla文档的代码段。

An arrow function does not create its own this, the this value of the enclosing execution context is used. 箭头函数不会创建自己的this,而是使用封闭执行上下文的this值。 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: 因此,在下面的代码中,传递给setInterval的函数中的this与包含函数中的this具有相同的值:

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函数将被其实现替换为像这样作为参数传递的匿名函数。

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. 第00行:这里不会指向匿名函数,因为使用了箭头函数,它将指向封闭的执行上下文。 for what i understood the enclosing execution context here is setInterval function but for that no age property is defined. 对于我所理解的封闭执行上下文,这里是setInterval函数,但是没有定义age属性。 I know I am wrong as age points to person object as it is running fine. 我知道我错了,因为年龄指向人对象,因为它运行良好。

Where was the function created , not where it was called , that is it's enclosing context . 函数哪里创建 ,而不是在哪里调用 ,那就是它的enclosing context Your function is created in the function Person , so this function is the enclosing context for the arrow function . 您的函数是在function Person函数中创建的,因此此函数是arrow function的封闭上下文。

You only create an arrow function and pass it to the setInterval , it is not created in the setInterval 's definition. 您仅创建一个arrow function并将其传递给setInterval ,而不是在setInterval的定义中创建。 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 . 在这里,您可以看到func的封闭上下文是Person

function Person(){
   this.age = 0;

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

   setInterval(func, 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM