Javascript中call函數和apply函數的使用

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

Javascript 中call函數和apply的使用:

Javascript中的call函數和apply函數是對執行內容進行切換,是將一個函數從當前執行的環境切換到另一個對象中執行,例如:

sourceObj.method.call(destObj,params1,params2) 是將sourceObj中的method函數放在destObj中執行

call函數還有另外一種重要的作用,在Javascript物件導向編程中實現多繼承的作用,例如:

function parentClass(){    this.showText(text){        alert(text);    }};function inherentClass(){    parentClass.call(this);};var instance=new inherentClass();instance.showText(‘inherent caller‘);
View Code

當然也可以通過這種方式實現多繼承的作用,只需要使用在子類中用每個父類調用call方法。

同樣apply和call函數的作用大致相同,只是傳入的參數不同,apply函數和call函數的參數列表中第一個參數是相同的, 在call函數中第二個參數可以是任意的參數,而apply函數的第二個參數必須是數組,且apply函數只能有2個參數。

如下簡單demo一下如何使用apply函數:

function sourceObj(firstPrams,secondParams){    alert(firsParams+secondParams);}function destObj(firstParams,seconParams){    alert(firstParams*secondParams);}sourceObj.apply(destObj,[6,2]);        //result=12
View Code

 

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.