在学习call和apply之前,我们先来简单的了解一下JavaScript中this指针:
*简单来说:如果不用new操作符而直接调用,那么构造函数的执行对象就 是window,即this指向了window。现在用new操作符后,this就指向了新生成的对象。
1、 call和apply都是改变this指向。
2、区别在于传参列表不同
call 需要把实参按照形参的个数传进去
apply需要传一个arguments
3、调用call和apply的作用就是:借用别人的函数实现自己的功能的封装
4、call的使用:
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name,age,sex,tel,grade){
// var this = {name:"",age:"",sex:""}
Person.call(this,name,age,sex); //通过call将Person中的传进来,想调用别人的函数就这样实现
this.tel = tel;
this.grade = grade;
}
var student = new Student("sunny",123,"male",139,2017);

5、apply的使用:
function Wheel(whellSize,style){
this.style = style;
this.whellSize = whellSize;
}
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(whellSize,style,c,sitColor,height,width,len){
Wheel.apply(this,[whellSize,style]);
Sit.apply(this,[c,sitColor]);
Model.apply(this,[height,width,len]);
}
var car = new Car(100,"花里胡哨","真皮","red",1800,1900,4900);


736

被折叠的 条评论
为什么被折叠?



