1. 程式人生 > >call()與apply()區別

call()與apply()區別

來源:http://www.cnblogs.com/qzsonline/archive/2013/03/05/2944367.html

一、方法的定義
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必須是object 19 20 var dog = new Dog(["Black Dog"]); //apply必須是array 21 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();
複製程式碼