call方法:
語法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisObj 指定的新對象。
如果沒有提供 thisObj 參數,那么 Global 對象被用作 thisObj。
apply方法:
語法:apply([thisObj[,argArray]])
定義:應用某一對象的一個方法,用另一個對象替換當前對象。
說明:
如果 argArray 不是一個有效的數組或者不是 arguments 對象,那么將導致一個 TypeError。
如果沒有提供 argArray 和 thisObj 任何一個參數,那么 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。
- <script language="javascript"><!--
- /**定義一個animal類*/
- function Animal(){
- this.name = "Animal";
- this.showName = function(){
- alert(this.name);
- }
- }
- /**定義一個Cat類*/
- function Cat(){
- this.name = "Cat";
- }
- /**創建兩個類對象*/
- var animal = new Animal();
- var cat = new Cat();
- //通過call或apply方法,將原本屬於Animal對象的showName()方法交給當前對象cat來使用了。
- //輸入結果為"Cat"
- animal.showName.call(cat,",");
- //animal.showName.apply(cat,[]);
- / --></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初始化方法。