Javascript 中的 call 和 apply

发表于 2012年02月1日

JavaScript 中通过call或者apply用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。简单的说就是改变函数执行的上下文,这是最基本的用法。两个方法基本区别在于传参不同。

  • call(obj,arg1,arg2,arg3);call第一个参数传对象,可以是null。参数以逗号分开进行传值,参数可以是任何类型。
  • apply(obj,[arg1,arg2,arg3]);apply第一个参数传对象,参数可以是数组或者arguments 对象。

这两个方法通常被用来类的继承和回调函数:

作用一、类的继承:

先来看这个例子:

[code=”javascript”]

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();//男

[/code]

这样 webDever类就继承Person类,Person.call(this,name,age) 的 意思就是使用 Person构造函数(也是函数)在this对象下执行,那么 webDever就有了Person的所有属性和方法,test对象就能够直接调用Person的方法以及属性了; 09年的理解解非常粗浅,呵呵。http://www.css88.com/archives/1692

作用二、回调函数:

call 和 apply在回调行数中也非常有用,很多时候我们在开发过程中需要对改变回调函数的执行上下文,最常用的比如ajax或者定时什么的,一般情况下,Ajax都是全局的,也就是window对象下的,来看这个例子:

[code=”javascript”]

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);

});

[/code]

这里

[code=”javascript”]

album.get_owner(function (owner) {

alert(‘The album’ + this.name + ‘ belongs to ‘ + owner);

});

[/code]

中的 this.name就能直接取到album对象中的name属性了。

posted @ 2016-04-08 16:03  mabel_on_line  阅读(330)  评论(0编辑  收藏  举报