改变 this 指向的 call 和 apply

一、call 方法
基本用法

function test() {
    console.log('hello world');
}
test(); // hello world
test.call(); // hello world
// test() ==> test.call()

其实就是借用别人的方法,来实现自己的功能

function Person(name, age) {
    // this == obj
    this.name = name;
    this.age = age;
}

var obj = {
    
};

var person = new Person();
Person.call(obj, 'mary', 18); // 让 obj 也拥有构造函数的方法

call 的根本作用就是改变 this 指向,第一个参数就是 this 的指向

小案例

function Student(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

function Color(red, blue, pink) {
    this.red = red;
    this.blue = blue;
    this.pink = pink;
}

function Model(height, width, len) {
    this.height = height;
    this.width = width;
    this.len = len;
}

function Car(name, age, sex, red, blue, pink, height, width, len) {
    // var this = {
    //     
    // };
    Student.call(this, name, age, sex);
    Color.call(this, red, blue, pink);
    Model.call(this, height, width, len);
}

var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);

二、apply 方法

function Student(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

function Color(red, blue, pink) {
    this.red = red;
    this.blue = blue;
    this.pink = pink;
}

function Model(height, width, len) {
    this.height = height;
    this.width = width;
    this.len = len;
}

function Car(name, age, sex, red, blue, pink, height, width, len) {
    // var this = {
    //     
    // };
    Student.apply(this, [name, age, sex]);
    Color.apply(this, [red, blue, pink]);
    Model.call(this, height, width, len);
}

var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);
  1. call 需要把实参按照形参的个数传进去
  2. apply 需要传一个 arguments 实参列表
[].slice.call(arguments) -- 能将具有 length 属性的对象转换为数组

三、总结

call / apply 都是改变 this 指向,区别就是传参列表不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iteval

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值