简体   繁体   中英

Why is this javascript function inside parenthesis?

I was looking for a solution to a problem and I found this aswer https://stackoverflow.com/a/6962808/2724978

The function written is:

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            doSomething();
            loop();  
    }, rand);
}());

My question is, why is the function insite parenthesis an also having () at the end? It got me a bit confused, never seen this before.

This is an example of an Immediately Invoked Function Expression .

The link above will explain all you need to know, but essentially there are two things happening.

  • Wrapping within parenthesis tells the parser to treat everything within them as an expression.
  • Calling the expression (with () ) immediately afterwards ensures the scope of that expression is sealed.

The snippet creates an anonymous function, and immediately calls it.

The problem with doing without parens,

// This is a syntax error
function () {
  something;
}();

is that that is a syntax error; because the statement starts with 'function', the parser expects a function name to follow. Wrapping it all in parens makes it syntatically legal to define an anonymous function there.

// This is valid syntax
(function () {
  something;
}());

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