call
作用:改变this指向
借用别人函数实现自己功能
应用
实际开发过程中,多人协同开发,可能会出现以下情况
//同事写的构造函数
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
//你写的构造函数
function Student(name, age, sex, tel, grade) {
this.name = name;
this.age = age;
this.sex= sex;
this.tel = tel;
this.grade = grade;
}
你写的构造函数中的属性包含了同事的构造函数的属性,我们可以通过call/appley来优化代码,减少代码冗余的情况,借用同事的构造函数来实现你想要的功能。
//同事写的构造函数
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
//你写的构造函数
function Student(name, age, sex, tel, grade) {
Person.call(this, name, age, sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('小明', 18, '男', 12312312312, 2019);
其中,若不写参数,Person.call()与Person()完全等价,代表调用函数。
而Person.call()里面的参数,第一个传递对象,用来改变this的指向来指向这个对象,第二个实参对应第一个形参以此类推。
为什么第一个参数是this呢?
记得在构造函数三段式中介绍过,第一步就是生成一个名为this的对象
function Student(name, age, sex, tel, grade) {
//var this = {__proto__ : Student.prototype}
Person.call(this, name, age, sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('小明', 18, '男', 12312312312, 2019);
此时,Person.call()里面的this与这个this相同。这时,通过call改变了Person()中的this指向,使它指向了Student()中的this,所以可以使用Person.call()来创建自己的对象。
同样以工厂生产汽车为例,可能汽车的不同部件由不同的厂商提供
//车轮
function Wheel(wheelSize, style) {
this.wheelSize = wheelSize;
this.style = style;
}
//座椅
function Sit(sitColor, material) {
this.sitColor = sitColor;
this.material = material;
}
//模型
function Model(height, width, len) {
this.height = height;
this.width = width;
this.len = len;
}
//组装汽车
function Car(wheelSize, style, sitColor, material, height, width, len) {
Wheel.call(this, wheelSize, style);
Sit.call(this, sitColor, material);
Model.call(this, height, width, len);
}
var car = new Car(100, '粗犷', 'black', '真皮', 1800, 1900, 4900);
apply
apply与call功能一样,唯一的区别是参数的传递方式。
call按照形参个数传递参数
apply需要传一个arguments
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade) {
Person.apply(this, [name, age, sex]);//apply需要传一个arguments
this.tel = tel;
this.grade = grade;
}
var student = new Student('小明', 18, '男', 12312312312, 2019);
//车轮
function Wheel(wheelSize, style) {
this.wheelSize = wheelSize;
this.style = style;
}
//座椅
function Sit(sitColor, material) {
this.sitColor = sitColor;
this.material = material;
}
//模型
function Model(height, width, len) {
this.height = height;
this.width = width;
this.len = len;
}
//组装汽车
function Car(wheelSize, style, sitColor, material, height, width, len) {
Wheel.apply(this, [wheelSize, style]);
Sit.apply(this, [sitColor, material]);
Model.apply(this, [height, width, len]);
}
var car = new Car(100, '粗犷', 'black', '真皮', 1800, 1900, 4900);