JavaScript回呼函數的3種用法

來源:互聯網
上載者:User

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的方法,並替換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.