js apply&&call

一、方法定義數組

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

apply方法: 
語法:apply([thisObj[,argArray]]) 
定義:應用某一對象的一個方法,用另外一個對象替換當前對象。 
說明: 
若是 argArray 不是一個有效的數組或者不是 arguments 對象,那麼將致使一個 TypeError。 
若是沒有提供 argArray 和 thisObj 任何一個參數,那麼 Global 對象將被用做 thisObj, 而且沒法被傳遞任何參數。app

 

二、經常使用實例函數

a、this

  1. function add(a,b)  
  2. {  
  3. alert(a+b);  
  4. }  
  5. function sub(a,b)  
  6. {  
  7. alert(a-b);  
  8. }  
  9. add.call(sub,3,1);  

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

 

b、繼承

  1. function Animal(){    
  2. this.name = "Animal";    
  3. this.showName = function(){    
  4. alert(this.name);    
  5. }    
  6. }    
  7. function Cat(){    
  8. this.name = "Cat";    
  9. }    
  10. var animal = new Animal();    
  11. var cat = new Cat();    
  12. //經過call或apply方法,將本來屬於Animal對象的showName()方法交給對象cat來使用了。    
  13. //輸入結果爲"Cat"    
  14. animal.showName.call(cat,",");    
  15. //animal.showName.apply(cat,[]);  

 call 的意思是把 animal 的方法放到cat上執行,原來cat是沒有showName() 方法,如今是把animal 的showName()方法放到 cat上來執行,因此this.name 應該是 Cat原型鏈

 

c、實現繼承原型

 function Animal(name){      io

              this.name = name;  function

         this.showName = function(){       

                          alert(this.name);      

                 }  

    }    

 

 

       function Cat(name){    

                  Animal.call(this, name);  

           }       

     var cat = new Cat("Black Cat");    

    cat.showName();  

             Animal.call(this) 的意思就是使用 Animal對象代替this對象,那麼 Cat中不就有Animal的全部屬性和方法了嗎,Cat對象就可以直接調用Animal的方法以及屬性了.

 

 

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..

相關文章
相關標籤/搜索