1. 程式人生 > >js 回撥函式 3種用法

js 回撥函式 3種用法

js 回撥函式大致有以下三種用法,
1,直接回調
2,call回撥
3,apply回撥
回撥函式作用得當,減少程式碼冗餘,程式碼可讀性增強,程式碼維護也輕鬆很多。


什麼要用到回撥函式呢?
當有很多地方需要呼叫同一個函式,並且這一函式根據不同的需要,作不同的處理,這個時候用回撥函式就特別合適了。


一,直接回調

function son () {  
 alert('tank test');  
}  
  
function son1 () {  
 alert('tank test1');  
}  
  
function father (callback) {   //公共函式  
 callback();  
 callback.call();  
}  
  
father(son);      //傳son,回撥son函式  
father(son1);     //傳son1函式,回撥son1函式

在不傳引數的情況下,callback(),callback.call()功能是一樣的。


二,call和apply回撥
1,call和apply區別

call([thisObj[,arg1[, arg2[, [,.argN]]]]])   
  
apply([thisObj[,argArray]])

call和apply基本上差不多,只是語法上面的不同。thisobj能繼承並替換目標函式中的this物件,下面會例項說明。

2,方法類中回撥
function son(name){  
   this.sonName = name;  
   this.showSonName = function(){  
       alert(this.sonName);       //彈出tank  
       alert(this.fatherName);    //彈出father,這是父級中的屬性,有沒有php extends的感覺  
   }  
}        
  
function father(name){  
   this.fatherName = 'father';  
   this.showFatherName = function(_callback){  
       _callback = eval(_callback);  
       _callback.call(this,name);  
       //_callback.apply(this,Array(name));  
   }  
}        
  
var fa = new father("tank");  
fa.showFatherName('son');     //傳字串的時候,使用回撥的時候,要用eval轉換一下  
fa.showSonName();

使用call進行回撥的時候,call中的this方法,會繼承son的方法,並替換


3,域中回撥
var son = {  
   name:"son",  
   getname:function(name){  
       this.fathername();    //彈father  
       this.name=name;  
       alert(this.name);     //彈tank  
   }  
}  
  
var father = {  
   init:function(_callback,name){  
       _callback = eval(_callback);  
       _callback.apply(this,Array('tank'));  
   },  
   fathername:function(){  
       alert('father');  
   }  
}  
  
father.init('son.getname');

使用apply進行回撥的時候,apply中的this方法,會繼承son的方法,並替換