箭头功能和`this` [英] Arrow function and `this`

查看:86
本文介绍了箭头功能和`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在粘贴来自mozilla文档的代码段.

I am pasting a snippet from mozilla docs.

箭头函数不会创建自己的this,而是使用封闭执行上下文的this值.因此,在下面的代码中,传递给setInterval的函数中的this与封闭函数中的this具有相同的值:

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

我的困惑是,当执行上述代码时,setInterval函数将被其实现替换为作为参数传递的匿名函数.

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 

    }

第00行:由于使用了箭头功能,此处将不指向匿名函数,而是指向封闭的执行上下文.对于我理解的封闭执行上下文,这里是setInterval函数,但是没有定义age属性.我知道我错了,因为年龄指向人对象,因为它运行良好.

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.

推荐答案

创建的函数在哪里,而不是在调用的地方,即enclosing context.您的函数是在function Person中创建的,因此此函数是arrow function的封闭上下文.

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.

您只能创建一个arrow function并将其传递给setInterval,而不是在setInterval的定义中创建的.

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

与此等效.在这里,您看到func的封闭上下文是Person.

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

这篇关于箭头功能和`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆