JavaScript的匿名方法书写模式

 

 

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值