JavaScript进阶(七)call, apply, bind

327 阅读2分钟

这是我参与8月更文挑战的第二十八天,活动详情查看:8月更文挑战

JavaScript进阶

JavaScript进阶(二)

JavaScript进阶(三)模块化

JavaScript进阶(四)防抖

JavaScript进阶(五)节流

JavaScript进阶(六)继承

写在前面,像我们的日常开发中,可能会遇到一些call,apply和bind这样的方法。看着这些方法,把this绑定来绑定过去。可能就会有点懵圈儿,那今天呢就让我带大家来了解一下这三个方法吧。废话不多说,let's go!

call, apply, bind

call

call()  方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

注意: 该方法的语法和作用与 [apply()] 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组

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

function cStudent(name, sex) {
    student.call(this, name, sex);
    this.name = 'ZhangSan';
}

console.log(new cStudent('LiSi', 'boy').name);
// ZhangSan

apply

apply()  方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供参数。

注意: call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组

const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const max = Math.max.apply(null, numArr);

console.log(max);
// 7

const min = Math.min.apply(undefined, numArr);

console.log(min);
// 2

null 或 undefined 时会自动替换为指向全局对象

bind

bind()  方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

const count = {
    x: 42,
    y: 24,
    add: function() {
        return this.x + this.y;
    }
};

const add = count.add;
console.log(add());
// Nan

const cAdd = add.bind(count);
console.log(cAdd());
// 66

END~~~