JavaScript 中的这种构造是什么意思:
(function (){
alert("bla");
})();
?
The acronym for this pattern is an "IIFE" or an Immediately Invoked Function Expression.
It basically creates an anonymous function function(){}
function(){alert("bla");}
then wraps it as an expression ()
(function(){alert("bla");})
then executes it ()
(function(){alert("bla");})()
Note that at this point, you can pass arguments in as well like this:
(function(text){alert(text);})("bla")
这是一个匿名块 - 声明一个匿名函数然后立即执行它,这意味着在块中声明的任何变量都看不到它之外。在这种情况下,使用 alert() 没有区别。
您定义了一个匿名函数,您可以立即调用它。
另请参阅javascript中自执行函数的目的是什么?用于解释构造的目的,简而言之,将名称保持为匿名函数中包装的代码的私有。
这是一个匿名函数,加载后会自动执行一次
Here you define an anonymous function to be executed immediately.
The function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. It returns the value of the newly created function, so by adding parenthesis after it, you may immediately invoke it.