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]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值