標籤:style io ar color sp strong on log bs
1. 方法定義。
call方法:
文法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。
如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。
apply方法:
文法:apply([thisObj[,argArray]])
定義:應用某一對象的一個方法,用另一個對象替換當前對象。
說明:
如果 argArray 不是一個有效數組或者不是 arguments 對象,那麼將導致一個 TypeError。
如果沒有提供 argArray 和 thisObj 任何一個參數,那麼 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。
2. 執行個體
function add(a, b){ console.log(a + b);}function sub(){ console.log(a - b);}add.call(sub, 3, 1);//result: 4
解析:js裡面的方法都是對象。將add裡面的this指標指向sub。所以結果還是 a + b
function Person(){ this.name = ‘person‘; this.show = function() { console.log(this.name); }}function Worker(){ this.name = ‘worker‘;}var p = new Person();var w = new Worker();p.show.call(w); //result: person
解析:執行p對象裡面的show方法,並把p對象裡面的this指標指向w。
function Person(name){ this.name = name; this.show = function() { console.log(this.name); }}function Worker(name){ Person.call(this, name);}var w = new Worker(‘zhangsan‘);w.show();
關於js中call和apply的理解