Home >Web Front-end >JS Tutorial >Summary of anonymous functions in Javascript_javascript skills
There are generally three ways to define a function in Javascript:
<code>function fnMethodName(x){alert(x);}</code>
<code>var fnMethodName = function(x){alert(x);}</code>
<code>var fnMethodName = new Function('x','alert(x);')</code>
The above three methods define the same method function fnMethodName. The first method is the most commonly used method. The latter two copy a function to the variable fnMethodName, and this function has no name, that is, an anonymous function. In fact, quite a few languages have anonymous functions .
<code>var f = function fact(x) { if (x < = 1) return 1; else return x*fact(x-1); };</code>
<code>var y = "global"; function constructFunction() { var y = "local"; return new Function("return y"); <span>// 无法获取局部变量</span> } alert(constructFunction()()); <span>// 输出 "global"</span> </code>
Compared with function keyword definition, the Function() constructor has its own characteristics and is much more difficult to use, so this technology is usually rarely used. The function literal expression is very close to the function keyword definition. Considering the previous difference, although there is news that literal anonymous functions have bugs in some webkit engines under OS X 10.4.3, the anonymous functions we usually refer to refer to anonymous functions in the form of function literals. For more details, you can read the Functions chapter of "JavaScript: The Definitive Guide, 5th Edition".
Yesterdayhedger wang introduced several anonymous function code patterns on his blog:
Error mode: It won’t work and the browser will report a syntax error.
<code>function(){ alert(1); }();</code>
<code>(function(){ alert(1); } ) ( );</code>
<code>( function(){ alert(2); } ( ) );</code>
<code>void function(){ alert(3); }()</code>
These three methods are equivalent. Hedge Wang prefers the third method due to personal reasons, but in practical applications, what I have seen and used is the first method.