js call + apply 篇

call() / apply()

作用

​ 修改this的指向。

call()

​ 任何方法后都可以加 .call( )

//效果相同
test()  ----> test.call()  

​ 当 call( ) 括号中有参数时,他会将前面的方法中的所有的this指向都修改为括号中的第一个参数。其余参数作为实参传入。

//使用call()借用别人的函数,完成自己的功能。

function Person(name, age){
    //this == obj
    this.name = name;
    this.age = age
}
var obj = {}
// call的第一个参数代表着修改的this指向。
Person.call(obj,"sada", 100)

//控制台
> obj
< {name: "sada", age: 100}
call()应用举例:
  1. 借用已存在的Person函数,来完成Student函数中的name,age,sex功能。(注意一但使用了call就相当于把上面的三条语句全拿了过去,不能挑选的拿)

    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("hu", 28, "girl", 123123213, 250);
    console.log(student);
    
  2. 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 (200, "big", "s", "red", 11, 222, 33);
    
apply ( ) 与 call ( ) 的区别

​ 传参列表不同

​ call 需要把实参按照形参的个数传进去

​ apply 需要传一个arguments

Sit.apply(this, [wheelSize, style]);
Sit.call(this, c, sitColor);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值