JavaScript 中通过call或者apply用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由?thisObj?指定的新对象。简单的说就是改变函数执行的上下文,这是最基本的用法。两个方法基本区别在于传参不同。
call(obj,arg1,arg2,arg3);
call第一个参数传对象,可以是null
。参数以逗号分开进行传值,参数可以是任何类型。apply(obj,[arg1,arg2,arg3]);
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("", 28, "男"); test.alertName();// test.alertAge();//28 test.alertSex();//男
这样 webDever类就继承Person类,Person.call(this,name,age) 的 意思就是使用 Person构造函数(也是函数)在this对象下执行,那么 webDever就有了Person的所有属性和方法,test对象就能够直接调用Person的方法以及属性了; 09年的理解解非常粗浅,呵呵。https://www.7psus5.com/archives/1692
作用二、回调函数:
call 和 apply在回调行数中也非常有用,很多时候我们在开发过程中需要对改变回调函数的执行上下文,最常用的比如ajax或者定时什么的,一般情况下,Ajax都是全局的,也就是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); });
这里
album.get_owner(function (owner) { alert('The album' + this.name + ' belongs to ' + owner); });
中的?this.name
就能直接取到album
对象中的name
属性了。
代码没缩进啊,看得挺累