6

我想弄清楚为什么在对象文本中的箭头函数被调用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;未使用)。

+1

当外部环境(在其中创建对象)有'此'作为窗口对象......箭头函数将使用创建者'this'的值作为它的'this'上下文 –

回答

11

请注意,Babel翻译采用了严格模式,但使用window的结果表明您正在松散模式下运行代码。如果你告诉通天的松散模式,其transpilation is different

var _this = this;     // ** 

var arrowObject = { 
    name: 'arrowObject', 
    printName: function printName() { 
    console.log(_this);    // ** 
    } 
}; 

注意_this全球和console.log(_this);,而不是console.log(undefined);从严格的模式transpilation。

我试图找出为什么在一个对象字面箭头函数调用windowthis

由于箭头函数从创建它们的上下文继承this。显然,在这里你这样做:

var arrowObject = { 
    name: 'arrowObject', 
    printName:() => { 
    console.log(this); 
    } 
}; 

... thiswindow。 (这表明您没有使用严格模式;我建议在没有明确理由的情况下使用它)。如果是其他内容,例如严格模式全局代码undefined,则箭头函数内的this应该是其他值代替。

它可能是一个有点清晰的背景是什么地方,如果我们打破你的初始化成其逻辑等价箭头功能创建:

var arrowObject = {}; 
arrowObject.name = 'arrowObject'; 
arrowObject.printName =() => { 
    console.log(this); 
}; 
+1

我的确在使用Fiddle(没有“use strict;”)。很好的回答,我明白现在发生了什么。 –

+0

很棒的回答。简单明了。 :) – Salivan

相关问题