【问题标题】:Arrow function and `this`箭头函数和`this`
【发布时间】:2017-09-06 13:17:26
【问题描述】:

我正在粘贴来自 mozilla 文档的 sn-p。

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

function Person(){
  this.age = 0;

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

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

setinterval(){

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

the function itself



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

    }

line 00 : 这里 this 不会指向匿名函数,因为使用了箭头函数,而是指向封闭的执行上下文。对于我所理解的封闭执行上下文,这里是 setInterval 函数,但没有定义年龄属性。我知道我错了,因为年龄指向人物对象,因为它运行良好。

【问题讨论】:

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

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

您只创建一个arrow function 并将其传递给setInterval,它不会在setInterval 的定义中创建。这个

function Person(){
  this.age = 0;

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

相当于这个。在这里您可以看到func 的封闭上下文是Person

function Person(){
   this.age = 0;

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

   setInterval(func, 1000);
}

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2023-03-15
    • 2017-12-06
    • 1970-01-01
    • 2018-05-04
    • 2021-04-22
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多