简体   繁体   中英

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. 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 = {}) , which essentially initializes star to an empty object if necessary, then passes it as an argument.

The fact that the line comment comments out the entire second half of the code makes this invalid JavaScript syntax.


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. This pattern is called immediately-invoked function expression (IIFE).


star || (star = {}) star || (star = {}) defaults star to an empty object in case it is falsey , which happens eg when it is not set.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM