为什么不是't这=>边界“;这个“;到周围的范围

Why isn't this => bounding "this" to the surrounding scope?

本文关键字:这个 边界 范围 周围 为什么不 gt      更新时间:2023-09-26

我从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();

具有词法this的箭头函数恰好意味着不会得到5,而是从周围的范围中得到一些东西。这与基于调用方对象确定的常规动态不同。


原件:因为v8有一个有缺陷的箭头函数实现,而且它在范围方面还不能正常工作。这就是为什么它一开始就在国旗后面。

您可以在问题跟踪器中跟踪进度。同时,您可以使用类似BabelJS的transpiler作为构建步骤,直到功能到位。

因为箭头函数内部的this绑定到外部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)