为什么使用 --harmony 会在 Node.js 中引发错误?
Why does this throw an error in Node.js with --harmony?
在 Chrome Canary 和 Node.js 0.12.3 中,以下代码打印 p
.
'use strict';
let o = {
name: 'o',
foo: function() {
['1'].map(function() {
console.log(this.name);
}.bind(this));
},
};
let p = { name: 'p' };
o.foo.call(p); // p
在 Chrome Canary 中,以下代码也打印 p
。但是为什么它会在带有 --harmony
标志的 Node.js 0.12.3 中抛出 TypeError?
'use strict';
let o = {
name: 'o',
foo: function() {
['1'].map(() => {
console.log(this.name);
});
},
};
let p = { name: 'p' };
o.foo.call(p); // p in Chrome, TypeError in Node.js with --harmony
换句话说,为什么Node.js中的第二个代码片段是运行时this
undefined
?
这简直就是due to a bug in the version of the V8 engineiojs和node使用的。 Chrome Canary 使用不稳定版本的 V8 解决了这个问题。当这个修复被推广到 V8 的稳定版本时,node/iojs 应该以同样的方式工作。
现在,您可以使用 babel
之类的工具来转译您的代码。使用 babel
且代码中没有任何标志会转换为:
function foo() {
var _this = this;
['1'].map(function () {
console.log(_this.name);
});
}
确实打印了 p
。
在 Chrome Canary 和 Node.js 0.12.3 中,以下代码打印 p
.
'use strict';
let o = {
name: 'o',
foo: function() {
['1'].map(function() {
console.log(this.name);
}.bind(this));
},
};
let p = { name: 'p' };
o.foo.call(p); // p
在 Chrome Canary 中,以下代码也打印 p
。但是为什么它会在带有 --harmony
标志的 Node.js 0.12.3 中抛出 TypeError?
'use strict';
let o = {
name: 'o',
foo: function() {
['1'].map(() => {
console.log(this.name);
});
},
};
let p = { name: 'p' };
o.foo.call(p); // p in Chrome, TypeError in Node.js with --harmony
换句话说,为什么Node.js中的第二个代码片段是运行时this
undefined
?
这简直就是due to a bug in the version of the V8 engineiojs和node使用的。 Chrome Canary 使用不稳定版本的 V8 解决了这个问题。当这个修复被推广到 V8 的稳定版本时,node/iojs 应该以同样的方式工作。
现在,您可以使用 babel
之类的工具来转译您的代码。使用 babel
且代码中没有任何标志会转换为:
function foo() {
var _this = this;
['1'].map(function () {
console.log(_this.name);
});
}
确实打印了 p
。