Code patterns for anonymous function
There are several ways to write anonymous function
匿名函数的书写方式有很多种
The Bad Pattern : It won't work and you'll get a syntax error
糟糕的模式:不但不会运行,还会有语法错误
<script>
function(){
alert(1);
}();
</script>
Pattern 1 : Function Literal
模式1:直接写成方法调用
Declare Function as an Object first then execute it.
先声明一个匿名方法然后立即执行
<script> (function(){ alert(1); } ) ( ); </script>
Pattern 2 : Prior Expression
模式2:利用表达式优先级
Use parentheses to force a declared function to be executed since JavaScript evaluates expressions from the inner parentheses to outer parentheses
使用圆括号来强制执行一个声明了的方法。
<script> ( function(){ alert(2); } ( ) ); </script>
Pattern 3 : Void Operator
模式3:使用void操作符
We can use "void" to evaluate a lone operand without using parentheses as the wrapper. of function
这个真没看懂说的是什么意思……
<script> void function(){ alert(3); }() </script>
Conclusion
建议
Technically these three patterns are equivalent, but I do prefer the pattern 3 for my own reasons.
从技术上讲这三个模式是一样的,但从我自身来说更喜欢模式3。
You may review these patterns and see which make sense most for you.