【发布时间】: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