DIV CSS 佈局教程網

JavaScript 的 call 與 apply:改變函數執行上下文的完整說明
編輯:關於JavaScript     

一句話概括:call 與 apply 都用來改變函數執行時的上下文(也就是 this 指向誰)。兩者的差別只在參數的傳遞形式。

call(obj, arg1, arg2, arg3);   // 參數以逗號分隔,可以是任意型別
apply(obj, [arg1, arg2, arg3]); // 參數必須是陣列或 arguments 物件

第一個參數是要作為 this 的物件,可以是 null。除此之外,這兩個方法最常被用在「類的繼承」與「回調函數」兩個場景。

作用一:實現類的繼承

function Person(name, age){
    this.name = name;
    this.age  = age;
    this.alertName = function(){ alert(this.name); }
    this.alertAge  = function(){ alert(this.age); }
}

function webDever(name, age, sex){
    Person.call(this, name, age);   // 借用父類構造器
    this.sex = sex;
    this.alertSex = function(){ alert(this.sex); }
}

var test = new webDever("愚人碼頭", 28, "男");
test.alertName();   // 愚人碼頭
test.alertAge();    // 28
test.alertSex();    // 男

Person.call(this, name, age) 的意思是:以當前物件作為 this,執行 Person 這個構造函數。於是 Person 裡設定的所有屬性與方法都落到了新物件上,webDever 就「繼承」了 Person 的一切。這種做法通常被稱為「借用構造器繼承」或「經典繼承」。

作用二:改變回調函數的執行上下文

call 與 apply 在回調中同樣好用。開發時經常需要改變回調函數的 this,最典型的例子就是 Ajax——Ajax 的 callbacks 預設是在 window 對象下執行的。

function Album(id, title, owner_id) {
    this.id = id;
    this.name = title;
    this.owner_id = owner_id;
};

Album.prototype.get_owner = function (callback) {
    var self = this;
    $.get('/owners/' + this.owner_id, function (data) {
        callback && callback.call(self, data.name);
    });
};

var album = new Album(1, '生活', 2);
album.get_owner(function (owner) {
    alert('The album ' + this.name + ' belongs to ' + owner);
});

關鍵在最後那行:透過 callback.call(self, data.name),回調函數裡的 this 就被指向了 album 物件,因此 this.name 能直接取到專輯名稱。若不這樣做,回調裡的 this 會是 window,this.name 就成了 undefined。

順帶談談 bind

呼叫當下就綁定上下文,用 bind 更合適:callback.bind(self, data.name) 會回傳一個已綁好 this 的新函數,適合需要把函數當值傳遞出去的場合。而 call 與 apply 是「立即執行」,差別在於時機。實務上的選擇依據是:要立刻執行就用 call/apply,要延後執行或當作回調傳遞就用 bind。

另外,apply 的第二個參數除了陣列,也可以直接傳 arguments,這在轉發參數的場景特別方便,例如 Math.max.apply(Math, arguments)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved