Javascript 匿名关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16032840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Anonymous Closure
提问by Trio Cheung
I have read a lot about closures in Javascript What are those braces for?? I read on mozilla.orgwhich says closure should be defined as
我已经阅读了很多关于 Javascript 中的闭包这些大括号的用途是什么?我在mozilla.org上读到,它说闭包应该被定义为
(function(){...})();
(function(){...})();
but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, it says the closure function is
但在http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html 上,它说闭包函数是
(function(){...}());
(function(){...}());
What's the difference or the latter one is wrong? what's the purpose of the last ()? Would you put some parameters inside? I am looking for a good reference.
有什么区别还是后者是错误的?最后一个 () 的目的是什么?你会在里面放一些参数吗?我正在寻找一个很好的参考。
Edit: Moreover, there is an example on Mozilla.org
编辑:此外,Mozilla.org上有一个示例
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.
为什么这个“功能”需要分号?如果需要在声明后立即调用,则在结束分号前加一个()。但没有。
回答by AlanFoster
The syntax
语法
(function(){...})()
is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.
只是一个立即调用的匿名函数。您如何使用括号并不重要,因为底层代码是一个被声明和调用的函数。
Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures
相反,闭包用于描述函数可以访问在其范围之外声明的变量的情况,这些变量可以通过闭包访问
For clarity :
为清楚起见:
If we have the following function
如果我们有以下函数
function hello() {
alert("Hello");
}
We can call the function with the following
我们可以使用以下命令调用该函数
hello()
Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do
它调用函数'hello'。但是如果我们不想给它一个名字,但仍然调用它,那么我们可以做
(function hello() {
alert("Hello");
})()
Which will do the exact same as the previous example of calling hello
这将与前面的调用示例完全相同 hello
However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:
但是,在这种情况下,将函数命名为“hello”是没有意义的,因此我们可以简单地将其删除:
(function() {
alert("Hello");
})()
Which is the notation used in your original question.
这是您原始问题中使用的符号。
回答by KevSheedy
Your example shows an Immediately Invoked Function Expression, or IIFE. It says to the interpreter:
您的示例显示了立即调用的函数表达式或 IIFE。它对翻译说:
- here is a function
- it has no name
- keep it away from the global scope ie 'window'
- call it now
- 这是一个函数
- 它没有名字
- 使其远离全局范围,即“窗口”
- 现在打电话
Yes, you can put parameters inside the last (). For example:
是的,您可以将参数放在最后一个 () 中。例如:
(
function(username){
alert("Hello " + username);
}
)("John Smith")
Closuresare a feature of javascript that allows us to implement data hidingwhich is roughly equivalent to private variables in languages like C++ or Java.
闭包是 javascript 的一个特性,它允许我们实现数据隐藏,这大致相当于 C++ 或 Java 等语言中的私有变量。
function getBmiCalculator(height, weight) {
// These are private vars
var height = height;
var weight = weight;
function calculateBmi(){
return weight / (height * height);
}
return calculateBmi;
}
var calc = getBmiCalculator(1.85, 90);
// calc still has access to the scope where height and weight live.
var bmi = calc();
alert(bmi);
In this example, height & weight cannot be garbage-collected until calc is destroyed. The section of memory or "scope" where height & weight exist are "Closed Over"
在这个例子中,身高和体重不能被垃圾收集,直到 calc 被销毁。存在身高和体重的记忆或“范围”部分是“封闭的”
回答by Ildar
There is no difference. You can also do so:
没有区别。你也可以这样做:
true && function(){ /* code */ }();
0,function(){ /* code */ }();
!function(){ /* code */ }(); // Facebook style
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();
// with new
new function(){ /* code */ }
new function(){ /* code */ }() // if you need arguments then use brackets
回答by hoogw
the grouping operator can surround the function description as without call parentheses, and also including call parentheses. I.e. both expressions below are correct FE:
分组运算符可以像没有调用括号一样包围函数描述,也可以包括调用括号。即下面的两个表达式都是正确的 FE:
(function () {})();
(function () {}());