IIFE背景问题 [英] IIFE context issues
问题描述
在以下构造中:
(function(){
var x = function(){
alert('hi!');
}
var y = function(){
alert("hi again!");
}
this.show = function(){
alert("This is show function!");
}
})();
为什么此
引用 window
对象? IIFE中的所有内容是否应与全球范围隔离?是 x
和 y
函数还是窗口的属性
全局对象?
Why does this
refer to window
object? Should everything inside IIFE be isolated from global scope? Are x
and y
functions also properties of window
global object?
此外,即使我在开头使用put var h = ...
:
Also, even if I use put var h = ...
at the beginning:
var h = (function(){
var x = function(){
alert('hi!');
}
var y = function(){
alert("hi again!");
}
this.show = function(){
alert("This is show function!");
}
})();
此
仍然指向窗口对象 - 我可以从全局范围调用 show()
!为什么?
this
still refers to window object -- I can just call show()
from the global scope! How come?
推荐答案
浏览器中的全局上下文(窗口
)是这个
的值,当没有其他值可以使用时。
The global context (window
in a browser) is the value this
gets when there's no other value to use.
你的局部变量是本地的(即,不是窗口的属性
)。它们在 var
的函数内声明。
Your local variables are local (that is, not properties of window
). They're declared inside the function with var
.
添加 var h的原因=(function(){...
没有区别是因为你调用函数的方式。函数引用不是对象的属性值(比如)。 func()
),你不用 .call()
或 .apply()
,因此这指的是全局( window
)对象。这就是定义语言的行为方式。
The reason why adding var h = (function(){...
makes no difference is because of the way you call the function. The function reference is not a property value of an object (like something.func()
), and you don't invoke it with .call()
or .apply()
, so therefore this refers to the global (window
) object. That's just the way the language is defined to act.
这篇关于IIFE背景问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!