call和apply的區別

來源:互聯網
上載者:User

標籤:gpo   ceo   func   另一個   無法   log   div   nbsp   object   

 

一、方法的定義 
call方法: 
文法:call(thisObj,Object)
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。 
如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。 

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

 

程式碼範例:

 1 function Animal(name) { 2     this.name = name; 3     this.showName = function() { 4         console.log(this.name); 5     }; 6 } 7  8 function Cat(name) { 9     Animal.call(this, name);10 }11 Cat.prototype = new Animal();12 13 function Dog(name) {14     Animal.apply(this, name);15 }16 Dog.prototype = new Animal();17 18 var cat = new Cat("Black Cat"); //call必須是object19 20 var dog = new Dog(["Black Dog"]); //apply必須是array21 22 cat.showName();23 dog.showName();24 25 console.log(cat instanceof Animal);26 console.log(dog instanceof Animal);

 

 

類比call, apply的this替換

 1 function Animal(name) { 2     this.name = name; 3     this.showName = function() { 4         alert(this.name); 5     }; 6 }; 7  8 function Cat(name) { 9     this.superClass = Animal;10     this.superClass(name);11     delete superClass;12 }13 14 var cat = new Cat("Black Cat");15 16 cat.showName();

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.