以下 JavaScript 构造称为闭包吗?
(function() {
//do stuff
})();
编辑:我最初认为这个构造被称为闭包 - 不是它引起的效果(可能)导致闭包 - 如果捕获变量。
这与闭包本身的行为无关——我完全理解这一点,但这并不是所要求的。
(function() {
//do stuff
})();
EDIT: I originally thought this construct was called a closure - not that the effect that it caused results (potentially) in a closure - if variables are captured.
This is in no way to do with the behaviour of closures themselves - this I understand fully and was not what was being asked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它是一个立即执行的匿名函数(或更准确地说是作用域匿名函数) 。
其用途是,其中声明的任何变量和函数的作用域都限于该函数,因此对任何全局上下文都是隐藏的(因此您可以获得封装和信息隐藏)。
It is an anonymous function (or more accurately a scoped anonymous function) that gets executed immediately.
The use of one is that any variables and functions that are declared in it are scoped to that function and are therefore hidden from any global context (so you gain encapsulation and information hiding).
它是一个匿名函数,但它不是一个闭包,因为您没有对外部范围的引用
http:// www.jibbering.com/faq/notes/closures/
it's an anonymous function but it's not a closure since you have no references to the outer scope
http://www.jibbering.com/faq/notes/closures/
我通常称之为“立即调用匿名函数”。
或者,更简单地说,“函数自调用”。
I usually call it something like "the immediate invocation of an anonymous function."
Or, more simply, "function self-invocation."
有点儿。但它并没有真正关闭任何东西,并且它是立即调用的,所以它实际上只是一个匿名函数。
看这段代码:
这里 foo() 返回的函数是一个闭包。它围绕 a 变量结束。即使 a 看起来早已超出范围,通过调用它来调用闭包仍然会返回该值。
Kindof. It's doesn't really close around anything though, and it's called immediately, so it's really just an anonymous function.
Take this code:
Here the function returned by foo() is a closure. It closes around the a variable. Even though a would apear to have long gone out of scope, invoking the closure by calling it still returns the value.
不,闭包更像是这样的东西:
闭包保留对返回它的函数的本地变量的引用。
编辑:您当然可以使用匿名函数创建闭包:
No, a closure is rather something along these lines:
the closure retains a reference to the variables local to the function that returned it.
Edit: You can of course create a closure using anonymous functions: