Javascript中定義函數的方式有多種,函數直接量就是其中一種。如var fun = function(){},這裏function如果不賦值給fun那麼它就是一個匿名函數。好,看看匿名函數的如何被調用。
方式1,調用函數,得到返回值。強制運算符使函數調用執行
1
2
3
4
|
( function (x,y){ alert(x+y); return x+y; }(3,4)); |
方式2,調用函數,得到返回值。強制函數直接量執行再返回一個引用,引用再去調用執行
1
2
3
4
|
( function (x,y){ alert(x+y); return x+y; })(3,4); |
這種方式也是很多庫愛用的調用方式,如jQuery,Mootools。
方式3,使用void
1
2
3
4
|
void function (x) { x = x-1; alert(x); }(9); |
方式4,使用-/+運算符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
- function (x,y){ alert(x+y); return x+y; }(3,4); + function (x,y){ alert(x+y); return x+y; }(3,4); -- function (x,y){ alert(x+y); return x+y; }(3,4); ++ function (x,y){ alert(x+y); return x+y; }(3,4); |
方式5,使用波浪符(~)
1
2
3
4
|
~ function (x, y) { alert(x+y); return x+y; }(3, 4); |
方式6,匿名函數執行放在中括號內
1
2
3
|
[ function (){ console.log( this ) // 瀏覽器得控制檯輸出window }( this )] |
方式7,匿名函數前加typeof
1
2
3
|
typeof function (){ console.log( this ) // 瀏覽器得控制檯輸出window }( this ) |
方式8,匿名函數前加delete
1
2
3
|
delete function (){ console.log( this ) // 瀏覽器得控制檯輸出window }( this ) |
方式9,匿名函數前加void
1
2
3
|
void function (){ console.log( this ) // 瀏覽器得控制檯輸出window }( this ) |
方式10,使用new方式,傳參
1
2
3
|
new function (win){ console.log(win) // window }( this ) |
方式11,使用new,不傳參
1
2
3
|
new function (){ console.log( this ) // 這裏的this就不是window了 } |
方式12,逗號運算符
1
2
3
|
1, function (){ console.log( this ) // window }(); |
方式13,按位異或運算符
1
2
3
|
1^ function (){ console.log( this ) // window }(); |
方式14,比較運算符
1
2
3
|
1> function (){ console.log( this ) // window }(); |
最後看看錯誤的調用方式
1
2
3
4
|
function (x,y){ alert(x+y); return x+y; }(3,4); |