简体   繁体   English

为什么在括号内使用此javascript函数?

[英]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 我一直在寻找问题的解决方案,但发现这个问题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. 此后立即调用表达式(with () )可确保该表达式的范围是密封的。

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. 因为该语句以'function'开头,所以解析器希望跟随函数名称。 Wrapping it all in parens makes it syntatically legal to define an anonymous function there. 将所有内容包装在括号中可以使在其中定义匿名函数在语法上合法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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