匿名函數自調用(IIFE)

什麼是匿名函數


Javascript中定義函數的方式有多種,函數直接量就是其中一種。如var fun = function(){},這裏function如果不賦值給fun那麼它就是一個匿名函數。好,看看匿名函數的如何被調用。

調用方式


1:調用函數,得到返回值。強制運算符使函數調用執行

(function(x,y){
    alert(x+y);
    return x+y;
}(3,4));

2:調用函數,得到返回值。強制函數直接量執行再返回一個引用,引用再去調用執行

(function(x,y){
    alert(x+y);
    return x+y;
})(3,4); 

這種方式也是很多庫愛用的調用方式,如jQueryMootools

3:使用void

void function(x) {
      x = x-1;
      alert(x);
}(9);   

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);

++function(x,y){
    alert(x+y);
    return x+y;
}(3,4);

5:使取反運算符(~)

~function(x, y) {
    alert(x+y);
   return x+y;
}(3, 4);

6:匿名函數執行放在中括號內

[function(){
   console.log(this) // 瀏覽器得控制檯輸出window
}(this)]

7:匿名函數前加typeof

typeof function(){
   console.log(this) // 瀏覽器得控制檯輸出window
}(this)

8:匿名函數前加delete

delete function(){
   console.log(this) // 瀏覽器得控制檯輸出window
}(this)   

9:匿名函數前加void

void function(){
   console.log(this) // 瀏覽器得控制檯輸出window
}(this)

10:使用new方式,傳參數

new function(win){
   console.log(win) // window
}(this)

11:使用new,不傳參數

new function(){
    console.log(this) // 這裏的this就不是window了
}  

12:逗號運算符

, function(){
    console.log(this) // window
}();

13:按位異或運算符

^function(){
    console.log(this) // window
}();

14:比較運算符


>function(){
    console.log(this) // window
}();

說明:本文摘自http://segmentfault.com/a/1190000002435410

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章