使用箭头函数的 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.12node --harmony
中时,该this.age++;
行似乎不是指Person
上下文,而是指setInterval
上下文。添加console.log(this)
到回调似乎证实了这一点。
当我使用其他 es6->es5 转译器时,它总是按预期工作。这是 node.js 中的错误吗?我错过了什么吗?
编辑:也许这就是原因?V8 中的 ES6 箭头函数词法 this
不同之处在于,他们讨论的是 Chrome,而这个问题是关于 Node.js 的。根据http://kangax.github.io/compat-table/es6/#arrow_functions,即使它们都使用 V8,它们也具有不同级别的 ES6 支持。