使用箭头函数 MDN 文档中的以下示例,地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
当我将该代码复制/粘贴到 node.js 0.12 node --harmony
中时,this.age++;
行似乎并未引用 Person
上下文,而是 setInterval
上下文。将 console.log(this)
添加到回调似乎证实了这一点。
当我使用其他 es6->es5 转译器时,它总是按预期工作。这是 Node.js 中的错误吗?我错过了什么吗?
编辑:也许这就是原因? ES6 arrow function lexical this in V8
不同的是,他们讨论的是 Chrome,而这个问题是关于 Node.js 的。根据http://kangax.github.io/compat-table/es6/#arrow_functions尽管它们都使用 V8,但它们对 ES6 的支持程度不同。
最佳答案
似乎原因是 V8 尚未更新以支持词法 this
。
关于javascript - Node.js 中的箭头函数上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28638591/