jquery中的call和apply方法


call方法:
語法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisObj 指定的新對象。
如果沒有提供 thisObj 參數,那么 Global 對象被用作 thisObj。

apply方法:
語法:apply([thisObj[,argArray]])
定義:應用某一對象的一個方法,用另一個對象替換當前對象。
說明:
如果 argArray 不是一個有效的數組或者不是 arguments 對象,那么將導致一個 TypeError。
如果沒有提供 argArray 和 thisObj 任何一個參數,那么 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。

 

 

  1.    
  2. <script language="javascript"><!--  
  3.     
  4. /**定義一個animal類*/    
  5. function Animal(){     
  6.     this.name = "Animal";     
  7.     this.showName = function(){     
  8.         alert(this.name);     
  9.     }     
  10. }     
  11. /**定義一個Cat類*/    
  12. function Cat(){     
  13.     this.name = "Cat";     
  14. }     
  15.     
  16. /**創建兩個類對象*/    
  17. var animal = new Animal();     
  18. var cat = new Cat();     
  19.     
  20. //通過call或apply方法,將原本屬於Animal對象的showName()方法交給當前對象cat來使用了。     
  21. //輸入結果為"Cat"     
  22. animal.showName.call(cat,",");     
  23. //animal.showName.apply(cat,[]);     
  24.       
  25.     
  26.   
  27. / --></script>   

 

 

 

以上代碼無論是采用animal.showName.call或是animal.showName.apply方法,運行的結果都是輸出一個"Cat"的字符串。說明showName方法的調用者被換成了cat對象,而不是最初定義它的animal了。這就是call和apply方法的妙用!

 

如果cat類中沒有定義 this.name = "Cat";,那么執行的發放中彈出的將是NaN對象,不會用Animal中的this.name。其中call和apply中的第二個參數是showname中的options參數。

 

 

如:

$.tukibox = function(method) {
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tukibox');
}
};

上面的call中,就是調用Array的slice方法,傳入兩個參數作為slice的參數。apply當然是讓當前對象調用methods對象中的指定方法或者是init初始化方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM