關於javascript中call()和apply()方法的總結

來源:互聯網
上載者:User

標籤:繼承   app   樣本   函數調用   call   代碼   需要   bsp   java   

前段時間在使用javascript的過程中遇到了繼承的問題,自己順便就對call()和apply()方法進行了瞭解。

兩個方法的共同之處:這兩個方法作用相同,都用來改變當前函數調用的對象,即改變this的指向。

兩個方法的不同之處:不同之處就是兩種方法的傳參方式不同,apply接受的是數組參數,call接受的是連續參數。

apply()方法的定義:

Function.apply(obj,args);

obj:這個對象會代替Function類裡邊所指向的this對象。

args:這是一個數組,作為參數傳遞給Function。

樣本:

<script>  function Intro(name,age){    this.name=name;    this.age=age;    this.speak=function(){      console.log(‘My name is ‘+this.name+‘.‘+‘ I am ‘+this.age+‘ years old.‘);    }  }  function IntroInh(name,age){    Intro.apply(this,arguments);  }  var lm=new IntroInh(‘LiMing‘,20);  lm.speak();</script>

 

上面的代碼做了一個簡單的繼承應用,也展示了apply()在其中的作用。

call()方法的定義:

Function.call(obj,[param1[,param2[,…[,paramN]]]]);

obj:這個對象會代替Function類裡邊所指向的this對象。

params:這是一個參數列表。

樣本:

<script>  function Intro(name,age){    this.name=name;    this.age=age;    this.speak=function(){      console.log(‘My name is ‘+this.name+‘.‘+‘ I am ‘+this.age+‘ years old.‘);    }  }  function IntroInh(name,age){    // Intro.apply(this,arguments);    Intro.call(this,name,age);//對比上面apply()的不同;  }  var lm=new IntroInh(‘LiMing‘,20);  lm.speak();</script>

 

這裡只做一個簡單的概念和應用方法的敘述,具體的項目應用還需要我們進一步的實踐。

 

關於javascript中call()和apply()方法的總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.