標籤:
一、方法的定義
call方法:
文法:call(thisObj,Object)
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。
如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。
apply方法:
文法:apply(thisObj,[argArray])
定義:應用某一對象的一個方法,用另一個對象替換當前對象。
說明: 如果 argArray 不是一個有效數組或者不是 arguments 對象,那麼將導致一個 TypeError。
如果沒有提供 argArray 和 thisObj 任何一個參數,那麼 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。
function Animal(name) { this.name = name; this.showName = function() { console.log(this.name); };}function Cat(name) { Animal.call(this, name);}Cat.prototype = new Animal();function Dog(name) { Animal.apply(this, name);}Dog.prototype = new Animal();var cat = new Cat("Black Cat"); //call必須是objectvar dog = new Dog(["Black Dog"]); //apply必須是arraycat.showName(); //Black Catdog.showName(); //Black Dogconsole.log(cat instanceof Animal); //trueconsole.log(dog instanceof Animal); //true
ref:http://www.cnblogs.com/qzsonline/archive/2013/03/05/2944367.html
javascript中apply()和call()方法的區別