我想弄清楚为什么在对象文本中的箭头函数被调用window
作为this
。有人能给我一些见解吗?对象文字中的箭头函数
var arrowObject = {
name: 'arrowObject',
printName:() => {
console.log(this);
}
};
// Prints: Window {external: Object, chrome: Object ...}
arrowObject.printName();
和预期的一样,工程的对象:
var functionObject = {
name: 'functionObject',
printName: function() {
console.log(this);
}
};
// Prints: Object {name: "functionObject"}
functionObject.printName();
据Babel REPL,他们transpiled到
var arrowObject = {
name: 'arrowObject',
printName: function printName() {
console.log(undefined);
}
};
而且
var functionObject = {
name: 'functionObject',
printName: function printName() {
console.log(this);
}
};
为什么不arrowObject.printName();
与arrowObject
联系为this
?
控制台日志来自Fiddle(其中use strict;
未使用)。
当外部环境(在其中创建对象)有'此'作为窗口对象......箭头函数将使用创建者'this'的值作为它的'this'上下文 –