为什么不把这个“限制”到周围的范围呢?

我从MDN获取了以下代码 。

x = 9 var module = { x: 81, getX: () => this.x } var getX = module.getX console.log(getX()) 

我得到9

 alex@alex-K43U:~/node/es6$ iojs --harmony_arrow_functions index.js 9 

this不应该被它的词汇范围和输出81吗?

虽然下面的原始答案是正确的,V8没有保证 – ES6箭头有this 词汇 – 这意味着this是绑定到周围的范围 。 你的对象文字不是范围。

如果你有像这样的代码:

 var obj = {}; obj.x = 5; obj.foo = () => this.x; obj.foo(); 

具有词汇的箭头function, this正好意味着你不会得到5回来,而是从周围的范围得到一些东西。 这与基于调用者对象确定的常规dynamic不同。


原文:因为v8有一个错误的箭头函数实现,并且在范围方面它不能正常工作。 这就是为什么它首先落后于国旗。

您可以在问题跟踪器中跟踪进度。 同时你可以使用像BabelJS这样的转译器作为构build步骤,直到function出现为止。

因为this里面的箭头函数是绑定在这个外面的:

 var x = 9; var module = { x: 81, getX: () => this.x // `this` is still `window`, and can't be changed }; var getX = module.getX; module.getX(); // 9 getX.call(module); // 9 getX.call(window); // 9 getX(); // 9 

这与正常的函数不同,它不绑定this

 var x = 9; var module = { x: 81, getX: function() { // `this` is `module` when called like `module.getX()` // `this` is `window` when called like `getX()` in non-strict mode // `this` is `undefined` when called like `getX()` in strict mode // `this` can be changed using `call`, `apply`, `bind` return this.x; } }; var getX = module.getX; module.getX(); // 81 getX.call(module); // 81 getX.call(window); // 9 getX(); // 9 (non-strict mode) or error (strict mode)