function foo() {
console.log(this.a);
}
var a = 2;
(function() {
"use strict";
foo(); // 2
})();
我只是想知道,为什么调用 foo()
仍然给出值 2?我认为由于 foo
在 IIFE 内被调用,那么 this.a
将评估为 undefined
,因为 < 中没有 a
变量强>IIFE。
答案 0 :(得分:7)
“use strict”应用于 IIFE,而不是 foo()
函数。因此,foo
会在草率模式/非严格模式下运行。由于 foo()
没有明确绑定到它的 this
,它默认为全局对象,在浏览器中是 window
。当您在全局范围内声明 var a
时,它会作为属性添加到 window 对象中,这意味着在 foo 中使用 this.a
将为您提供 a
中保存的值,因为它正在访问a
的 window
属性。
如果 foo() 在严格模式下运行,您将获得 undefined
为 this
,而不是 IIFE:
function foo() {
"use strict";
console.log(this); // undefined
console.log(this.a); // Crash
}
var a = 2;
(function() {
foo();
})();
答案 1 :(得分:2)
让我们在这里看到两件事:-
首先,当在该范围内声明时,您的严格模式可以应用于 globalThis
,如下所示:-
"use strict";
function foo() {
console.log(this.a);
}
var a = 2;
(function() {
foo(); // Throws error since this is undefined
})();
另一种方式可能是@Nick 建议它在严格模式下仅运行 foo
。
第二个,
IIFE 中的 this
是您的 globalThis
,对于浏览器是 window
。在全局范围内用 var
声明的变量将自身附加到 window
。
答案 2 :(得分:2)
这是因为 foo
和 a
都是在全局范围内声明的,即它们是全局对象 window
的属性。
IIFE 内部的 this
将是 undefined
,因为它处于 strict
模式。但是在 IIFE 中调用 foo
会使 this
中的 foo
引用 window
对象。
并且由于您已经在 a
中有 window
,所以它会被打印出来。
答案 3 :(得分:1)
function test(){
return {
a: 9999,
testFunc: foo
}
}
function foo() {
console.log(this) //this is actually another context which point to its parent.
console.log(this.a);
}
var a = 2;
(function() {
"use strict";
console.log(this) //because of 'use strict', this will lead to undefined
foo(); // 2
test().testFunc(); //9999
})();