IIFE 上下文问题
在以下构造中:
(function(){
var x = function(){
alert('hi!');
}
var y = function(){
alert("hi again!");
}
this.show = function(){
alert("This is show function!");
}
})();
为什么 this
引用 window
对象? IIFE 内的所有内容都应该与全局范围隔离吗? x
和 y
函数也是 window
全局对象的属性吗?
另外,即使我在开头使用 put var h = ...
:
var h = (function(){
var x = function(){
alert('hi!');
}
var y = function(){
alert("hi again!");
}
this.show = function(){
alert("This is show function!");
}
})();
this
仍然引用 window 对象 - 我可以只调用 show()< /code> 来自全局范围!怎么会?
In the following construct:
(function(){
var x = function(){
alert('hi!');
}
var y = function(){
alert("hi again!");
}
this.show = function(){
alert("This is show function!");
}
})();
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?
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!");
}
})();
this
still refers to window object -- I can just call show()
from the global scope! How come?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
全局上下文(浏览器中的
window
)是没有其他值可用时this
获取的值。您的局部变量是局部的(即不是
window
的属性)。它们在函数内部用var
声明。添加
var h = (function(){...
没有区别的原因是调用函数的方式不同。函数引用不是对象的属性值(如something.func()
),并且您不使用.call()
或.apply()
调用它,因此 this 指的是全局(window
)对象就是这样。语言被定义为行动。The global context (
window
in a browser) is the valuethis
gets when there's no other value to use.Your local variables are local (that is, not properties of
window
). They're declared inside the function withvar
.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 (likesomething.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.@Pointy是正确的,但他没有提出整个问题 - 您可能会对
一般来说,在 IIFE 中不需要
this
,因为您可以直接访问匿名函数作用域中定义的任何函数或变量 -show()
可以调用 < code>x() 和y()
直接,因此不需要this
引用。可能有一个使用 new 实例化 IIFE 的有效用例,但我从未遇到过。@Pointy is correct, but he doesn't present the whole issue - you might be interested in this related answer. The issue here is that if you aren't using the
new
keyword, you aren't instantiating an object, so there's no instance forthis
to refer to. In the absence of an instance,this
refers to thewindow
object.In general, you don't need
this
within an IIFE, because you have direct access to any function or variable defined in the anonymous function's scope -show()
can callx()
andy()
directly, so there's no need for athis
reference. There may be a valid use case for instantiating an IIFE withnew
, but I've never come across it.