call/apply()笔记
call()
作用:改变this指向
正常函数执行时也是调用了call()
e.g. test()—> test.call()
test.call(obj,‘yuan’,300)
call()的第一个参数为改变的this的指向(此时变成obj了),从第二个参数开始之后的参数都是传入的形参。
应用:
这样可以调用已有的方法来实现自己的功能。
function Person (name , age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student (name , age , sex , tel , grade ) {
console.log(this);//new的时候this指向了student
Person.call(this,name,age,sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny' , 123 , 'male' , 135 , 2020)
console.log(Student.age);
例如(以车间为例):
function Wheel(wheelSize,style) {
this.style = style;
this.wheelSize = wheelSize;
}
function Sit (c,sitColor) {
this.c = c;
this.sitColor = sitColor;
}
function Model(height,width,len) {
this.height = height;
this.width = width;
this.len = len;
}
function Car(wheelSize , style , c ,sitColor , height , width ,len) {
Wheel.call(this, wheelSize , style);
Sit.call(this, c , sitColor);
Model.call(this,height,width,len);
}
var car = new Car(100,'花里胡哨','真皮','red',1800,1900,4900);
console.log(car);
call(),apply()区别:
传参列表不同,第一个都是改变this指向的参数
之后
call可以一位一位的传参进去//call需要把实参按照形参的个数传进去
apply只能传数组进去//apply需要传一个arguments
e.g.
Wheel.apply(this,[ wheelSize , style]);
Sit.apply(this,[ c , sitColor]);
Model.apply(this,[height,width,len]);
}