call 方法
語法:fun.call(thisArg[, arg1[, arg2[, ...]]])
定義:呼叫某物件的方法,並以另一個物件取代當前物件作為 this。
說明:call 可以把函式的物件上下文從原本的環境,切換成由 thisArg 指定的新物件。若未提供 thisArg,則以 Global 物件作為 thisArg。
apply 方法
語法:fun.apply(thisArg[, argsArray])
定義:套用某物件的方法,並以另一個物件取代當前物件。
說明:如果 argArray 不是有效陣列也不是 arguments 物件,會丟出 TypeError。若 argArray 與 thisArg 都未提供,則 Global 物件作為 thisArg,且無法傳入任何參數。
差別只在「怎麼傳參數」:call 把參數逐一列舉,apply 則接收一個陣列或 arguments 物件。
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
apply 搭配 arguments 的好處很明顯:參數清單不必重抄一遍,父類建構子增減參數時子類完全不用改。
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("設計蜂巢", 24, "男");
test.alertName(); // 設計蜂巢
test.alertAge(); // 24
test.alertSex(); // 男
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);
});
這裡的關鍵是:Ajax 回呼裡的 this 已經不是 album 了,所以用 call 把上下文重新綁回 self,回呼內部才能正確讀到 this.name。