对象文字中的箭头函数 [英] Arrow Function in Object Literal
问题描述
我想弄清楚为什么对象字面量中的箭头函数是用 window
作为 this
调用的.有人可以给我一些见解吗?
I'm trying to figure out why an arrow function in an object literal is called with window
as this
. Can someone give me some insight?
var arrowObject = {
name: 'arrowObject',
printName: () => {
console.log(this);
}
};
// Prints: Window {external: Object, chrome: Object ...}
arrowObject.printName();
一个按预期工作的对象:
And an object that works as expected:
var functionObject = {
name: 'functionObject',
printName: function() {
console.log(this);
}
};
// Prints: Object {name: "functionObject"}
functionObject.printName();
根据Babel REPL,它们被转译为
var arrowObject = {
name: 'arrowObject',
printName: function printName() {
console.log(undefined);
}
};
和
var functionObject = {
name: 'functionObject',
printName: function printName() {
console.log(this);
}
};
为什么arrowObject.printName();
不是用arrowObject
作为this
调用的?
Why isn't arrowObject.printName();
called with arrowObject
as this
?
控制台日志来自 Fiddle(其中 use strict;
是t 使用).
Console logs are from Fiddle (where use strict;
isn't used).
推荐答案
请注意,Babel 翻译假设是严格模式,但是 window
的结果表明您正在以松散模式运行代码.如果你告诉 Babel 采用松散模式,它的转译 不同:
Note that the Babel translation is assuming strict mode, but your result with window
indicates you're running your code in loose mode. If you tell Babel to assume loose mode, its transpilation is different:
var _this = this; // **
var arrowObject = {
name: 'arrowObject',
printName: function printName() {
console.log(_this); // **
}
};
注意 _this
全局和 console.log(_this);
,而不是严格的 console.log(undefined);
-模式转译.
Note the _this
global and console.log(_this);
, instead of the console.log(undefined);
from your strict-mode transpilation.
我想弄清楚为什么对象字面量中的箭头函数是用 window
作为 this
调用的.
I'm trying to figure out why an arrow function in an object literal is called with
window
asthis
.
因为箭头函数从创建它们的上下文中继承了this
.显然,您在何处执行此操作:
Because arrow functions inherit this
from the context in which they're created. Apparently, where you're doing this:
var arrowObject = {
name: 'arrowObject',
printName: () => {
console.log(this);
}
};
...this
是 window
.(这表明您没有使用严格模式;我建议在没有明确理由不使用的情况下使用它.)如果是其他东西,例如严格模式全局代码的 undefined
,<箭头函数中的 code>this 将是另一个值.
...this
is window
. (Which suggests you're not using strict mode; I'd recommend using it where there's no clear reason not to.) If it were something else, such as the undefined
of strict mode global code, this
within the arrow function would be that other value instead.
如果我们把你的初始化器分解成它的逻辑等价物,那么创建箭头函数的上下文可能会更清楚一些:
It may be a bit clearer what the context is where the arrow function is created if we break your initializer into its logical equivalent:
var arrowObject = {};
arrowObject.name = 'arrowObject';
arrowObject.printName = () => {
console.log(this);
};
这篇关于对象文字中的箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!