JS中的apply與call

定義

  ECMAScript規範給所有函數都定義了call 與 apply 兩個方法,call與apply的第一個參數都是需要調用的函數對象,在函數體內這個參數就是this的值,剩餘的參數是需要傳遞給函數的值,具體如下:

call方法:

語法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])

定義:以傳入對象作爲當前對象去調用其他對象的方法。

注:如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj

apply方法:

語法:apply([thisObj[,argArray]])

定義:以傳入對象作爲當前對象去調用其他對象的方法。

注:

1. 如果 argArray 不是一個有效的數組或者不是arguments 對象,那麼將導致一個 TypeError

2. 如果沒有提供 argArray thisObj 任何一個參數,那麼 Global 對象將被用作 thisObj 並且無法被傳遞任何參數。

區別

  從上文中可看出兩個方法基本上是一個意思,區別在於 call 的第二個參數可以是任意類型,而apply的第二個參數必須是數組,也可以是arguments

用途

函數替換

function add(a,b) { 
 alert(a+b);  
}
   
function sub(a,b) {  
 alert(a-b);  
}  
    
add.call(sub,3,1);   
// => add(3, 1) => alert(4)
 
add.apply(sub, [3,1])
// => add(3,1) => alert(4)

這個例子中就是用 add 來替換 sub

方法借用

function Animal(){    
 this.name = "Animal";    
 this.showName = function(){    
  alert(this.name);    
 }    
}    
    
function Cat(){    
 this.name = "Cat";    
}    
   
var animal = new Animal();    
var cat = new Cat();    
  
animal.showName.call(cat,","); 
animal.showName.apply(cat, []);
// => alert(“cat”)

原來cat是沒有showName() 方法,現在通過call或apply把animal 的showName()方法借到 cat上來執行,同時也將showName方法的上下文從animal改爲cat,故showName中的this指向cat,所以this.name 應該是 Cat

實現繼承

function Animal(name){      
 this.name = name;      
 this.showName = function(){      
  alert(this.name);      
 }      
}      
      
function Cat(name){    
 Animal.call(this, name);    
 // Animal.apply(this,[name]);
}      
    
var cat = new Cat("Black Cat");     
cat.showName();
// => alert(“Black Cat”)

Animal.call(this) 的意思就是使用 this對象代替Animal對象,那麼 Cat中自然就有Animal的所有屬性和方法。

多重繼承

function Father() {  
 this.showSub = unction(a,b){  
  alert(a-b);  
 }  
}  
   
function Mother(){  
 this.showAdd = function(a,b){  
  alert(a+b);  
 }  
}  
  
function Child(){  
 Father.call(this);  
 Mother.call(this);  
}


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