(function (){
'use strict';
function Foo() {
this.foo = function() {
setTimeout(function(){ console.log(this); }, 0);
}
}
new Foo().foo();
}())
如果我没有声明严格模式,那么全局对象将被打印到控制台(即窗口)。
但是,鉴于声明了严格模式,我希望将 undefined 打印到控制台。
参考:
“这意味着,除其他外,在浏览器中,不再可能通过 this 在严格模式函数中引用窗口对象。”
更新:要实现预期的行为,您需要创建一个新的执行上下文并在该上下文中引用它,如下所示:
(function (){
'use strict';
function Foo() {
this.foo = function() {
setTimeout(function(){ (function() { console.log(this); }()) }, 0);
}
}
new Foo().foo();
}())