对象文字中的箭头功能 [英] Arrow Function in Object Literal
问题描述
我想知道为什么一个对象文字中的箭头函数是以窗口
作为这个
。有人可以给我一些洞察力吗?
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
作为这个
?
控制台日志来自小提琴(其中使用strict;
Console logs are from Fiddle (where use strict;
isn't used).
推荐答案
请注意,Babel翻译是假定严格的模式,但结果与窗口
表示您正在以松散的模式运行代码。如果你告诉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
global和 console.log(_this);
,而不是从严格模式展开的 console.log(undefined);
p>
Note the _this
global and console.log(_this);
, instead of the console.log(undefined);
from your strict-mode transpilation.
我试图弄清楚为什么使用
窗口$ c $调用对象文字中的箭头函数c> as
this
。因为箭头函数从它们创建的上下文继承这个
I'm trying to figure out why an arrow function in an object literal is called with
window
asthis
.
。显然,你在这样做:
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);
}
};
... 这个
是窗口
。 (这表明你没有使用严格的模式;我建议使用它,没有明确的理由不要。)如果是别的东西,例如 undefined
严格模式全局代码这个
在箭头函数中将是另一个值。
...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屋!