[英]I'm new to JavaScript. Can someone explain to me what this syntax is doing ()()
Can someone explain to me what this syntax is doing? 有人可以向我解释此语法在做什么吗?
(function(star){
//do something
})(star || (star = {}));
It is called an IIFE (Immediately-invoked function expression) that is run as soon as it is loaded. 它称为IIFE(立即调用的函数表达式),它在加载后立即运行。 It is used to avoid polluting the global namespace.
它用于避免污染全局名称空间。 That is, the variables in the function are not in the global scope, so they are executed then gone (save for anything that would still have a valid reference)
也就是说,函数中的变量不在全局范围内,因此它们将被执行然后消失(保存任何仍具有有效引用的变量)
It's declaring an anonymous function and immediately invoking it with the expression star || (star = {})
它声明了一个匿名函数,并立即使用表达式
star || (star = {})
调用它。 star || (star = {})
, which essentially initializes star
to an empty object if necessary, then passes it as an argument. star || (star = {})
,它在必要时将star
初始化为一个空对象,然后将其作为参数传递。
The fact that the line comment comments out the entire second half of the code makes this invalid JavaScript syntax. 行注释注释掉了整个代码的后半部分,这一事实使该JavaScript语法无效。
Assuming that the function was formatted like this: 假设函数的格式如下:
(function(star){
//do something
})(star || (star = {}));
Here, you are defining an anonymous function and invoke it immediately. 在这里,您要定义一个匿名函数并立即调用它。 This has the benefit that
//do something
is executed in its own function scope , preventing variables from being leaked into the global state. 这样的好处是
//do something
在其自己的函数范围内执行//do something
操作,从而防止变量泄漏到全局状态中。 This pattern is called immediately-invoked function expression (IIFE). 这种模式称为立即调用函数表达式(IIFE)。
star || (star = {})
star || (star = {})
defaults star
to an empty object in case it is falsey , which happens eg when it is not set. star || (star = {})
star
缺省为空对象,以防它为false ,例如在未设置星标时会发生这种情况。
This is an anonymous selfcalling function. 这是一个匿名的自呼功能。 Usually you do:
通常您会:
function a(b,c){
//execute
}
a(1,2);
But then others can execute this function, and if you want to put it into a variable its a bit long: 但是其他人可以执行此功能,如果您想将其放入一个变量中,该函数会有点长:
function a(b,c){
return b+c;
}
d=a(1,2);
With the selfcalling function, this is much easier: 使用自调用功能,这变得容易得多:
d=(function(b,c){return b+c;})(1,2);
It has the following syntax: 它具有以下语法:
(anonymous function to call)(passed variables)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.