var obj = {
log: function() {
console.log(this);
var nestedLog = function() {
console.log(this);
}
nestedLog();
}
};
obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }
然后我得到
{log: ƒ}
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
有人可以解释为什么this
绑定消失了吗?我没有从全局执行上下文执行nestedLog
,但是仍然从window
绑定中获得了this
对象。我真的不明白为什么会这样。我知道this
绑定取决于执行上下文以及我是否这样做:
var log = obj.log;
log()
很明显,我得到了window
对象。但是当我在nestedLog
函数中执行obj.log
时,this
绑定不应该保持不变吗?有人可以解释一下它是如何工作的吗?
答案 0 :(得分:0)
log
是obj
的方法,因此将其设置为obj
。
将函数作为对象的方法调用时,其
this
设置为在其上调用方法的对象
nestedLog
不是对象方法,因此将this
设置为window
对象
在函数的simple call中
this
将默认为全局对象,该全局对象在浏览器中为window
。
使用可以使用Arrow Function
来解决此问题
var obj = {
log: function() {
console.log(this);
var nestedLog = () => {
console.log(this);
}
nestedLog();
}
};
obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }