为什么 this => bounding "this" 到周围的范围?
Why isn't this => bounding "this" to the surrounding scope?
我从 MDN 中获取了以下 code。
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 而是从周围的范围中获取一些东西。这与常规 dynamic this 不同,后者是根据调用者对象确定的。
原文:
因为 v8 有一个有问题的箭头函数实现,而且它在作用域方面还不能正常工作。这就是为什么它首先在旗帜后面的原因。
您可以跟踪进度 here in the issue tracker。同时,您可以使用像 BabelJS 这样的转译器作为构建步骤,直到功能可用。
因为箭头函数内部的 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)
我从 MDN 中获取了以下 code。
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 而是从周围的范围中获取一些东西。这与常规 dynamic this 不同,后者是根据调用者对象确定的。
原文: 因为 v8 有一个有问题的箭头函数实现,而且它在作用域方面还不能正常工作。这就是为什么它首先在旗帜后面的原因。
您可以跟踪进度 here in the issue tracker。同时,您可以使用像 BabelJS 这样的转译器作为构建步骤,直到功能可用。
因为箭头函数内部的 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)