文章出處

在iteye看到一篇對call解釋得相當簡明易懂,覺得得宣傳一下 : http://uule.iteye.com/blog/1158829

一、方法的定義 

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

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

2、常用實例

a例

function add(a,b)
{
    alert(a+b);
}
function sub(a,b)
{
    alert(a-b);
}

add.call(sub,3,1); 

這個例子中的意思就是用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以運行結果為:alert(4); // 注意:js 中的函數其實是對象,函數名是對 Function 對象的引用。

b例

function Animal(){  
    this.name = "Animal";  
    this.showName = function(){  
        alert(this.name);  
    }  
}  

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,[]);

call 的意思是把 animal 的方法放到cat上執行,原來cat是沒有showName() 方法,現在是把animal 的showName()方法放到 cat上來執行,所以this.name 應該是 Cat

c、實現繼承

 function Animal(name){    
     this.name = name;    
     this.showName = function(){    
         alert(this.name);    
     }    
 }    
   
 function Cat(name){  
     Animal.call(this, name);  
 }    
   
 var cat = new Cat("Black Cat");   
 cat.showName();

d、多重繼承

function Class10()
{
    this.showSub = function(a,b)
    {
        alert(a-b);
    }
}

function Class11()
{
    this.showAdd = function(a,b)
    {
        alert(a+b);
    }
}

function Class2()
{
    Class10.call(this);
    Class11.call(this);
}

 很簡單,使用兩個 call 就實現多重繼承了
當然,js的繼承還有其他方法,例如使用原型鏈,這個不屬于本文的范疇,只是在此說明call 的用法。說了call ,當然還有 apply,這兩個方法基本上是一個意思,區別在于 call 的第二個參數可以是任意類型,而apply的第二個參數必須是數組,也可以是arguments
還有 callee,caller..

例子來源:http://xiaofeizm55333.iteye.com/blog/80913

http://www.iteye.com/topic/599108   及回復..


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()