JavaScript 中通過call或者apply用來代替另一個(gè)對(duì)象調(diào)用一個(gè)方法,將一個(gè)函數(shù)的對(duì)象上下文從初始的上下文改變?yōu)橛?thisObj 指定的新對(duì)象。簡(jiǎn)單的說就是改變函數(shù)執(zhí)行的上下文,這是最基本的用法。兩個(gè)方法基本區(qū)別在于傳參不同。
call(obj,arg1,arg2,arg3);call第一個(gè)參數(shù)傳對(duì)象,可以是null。參數(shù)以逗號(hào)分開進(jìn)行傳值,參數(shù)可以是任何類型。
apply(obj,[arg1,arg2,arg3]);apply第一個(gè)參數(shù)傳對(duì)象,參數(shù)可以是數(shù)組或者arguments 對(duì)象。
這兩個(gè)方法通常被用來類的繼承和回調(diào)函數(shù):
作用一、類的繼承:
先來看這個(gè)例子:
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();//男
這樣 webDever類就繼承Person類,Person.call(this,name,age) 的 意思就是使用 Person構(gòu)造函數(shù)(也是函數(shù))在this對(duì)象下執(zhí)行,那么 webDever就有了Person的所有屬性和方法,test對(duì)象就能夠直接調(diào)用Person的方法以及屬性了; 09年的理解解非常粗淺,呵呵。http://www.css88.com/archives/1692
作用二、回調(diào)函數(shù):
call 和 apply在回調(diào)行數(shù)中也非常有用,很多時(shí)候我們?cè)陂_發(fā)過程中需要對(duì)改變回調(diào)函數(shù)的執(zhí)行上下文,最常用的比如ajax或者定時(shí)什么的,一般情況下,Ajax都是全局的,也就是window對(duì)象下的,來看這個(gè)例子:
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);
});
這里
album.get_owner(function (owner) {
alert('The album' + this.name + ' belongs to ' + owner);
});
中的 this.name就能直接取到album對(duì)象中的name屬性了。
文章來源:http://www.css88.com/archives/4431