call(),apply(),bind()函数的几种用法

127 阅读2分钟

求数组中的最大值和最小值

使用apply()函数来改变Math.max()函数和Math.min()函数的执行主体,然后将数组作为参数传递给Math.max()函数和Math.min()函数

    
var arr = [3, 5, 7, 2, 9, 11];
// 求数组中的最大值
console.log(Math.max.apply(null, arr)); // 11
// 求数组中的最小值
console.log(Math.min.apply(null, arr)); // 2

apply()函数的第一个参数为null,这是因为没有对象去调用这个函数,我们只需要这个函数帮助我们运算,得到返回结果

第二个参数是数组本身,就是需要参与max()函数和min()函数运算的数据,运算结束后得到的返回值,表示数组的最大值和最小值。

类数组对象转换为数组对象

函数的参数对象arguments是一个类数组对象,自身不能直接调用数组的方法,单数我们可以借助call()函数, 让arguments对象调用数组的

// 任意个数字的求和
function sum() {
    // 将传递的参数转换为数组
    var arr = Array.prototype.slice.call(arguments);
    // 调用数组的reduce()函数
    return arr.reduce(function (pre, cur) {
        return pre + cur;
    }, 0)
}


console.log(sum(1, 2)) //3
console.log(sum(1, 2, 3))//6
console.log(sum(1, 2, 3, 4))//10

将call()函数用于构造继承

// 构造继承
function Animal(age) {
    //属性
    this.age = age;
    //实例函数
    this.sleep = function () {
        return this.name + '正在睡觉!'
    }
}
// 子类
function Cat(name, age) {
    //使用 call()函数实现继承
    Animal.call(this, age);
    this.name = name || 'tom';
}
var cat = new Cat('tony', 11);
console.log(cat.sleep()); //tony正在睡觉
console.log(cat.age);//11

关键语句是子类中的 Animal.call(this,age), 在call()函数中传递this,表示将Animal构造函数的执行主体转换为Cat对象,从而在Cat对象的this上会增加age属性和sleep函数,子类Cat相当于如下代码


function Cat(name, age) {
   // 来源于对父类的继承
  this.age = age;
   this.sleep = function () {
# return this.name + '正在睡觉!';
   };
   // Cat自身的实例属性
   this.name = name || 'tom';
}

执行匿名函数



var animals = [
    { species: 'Lion', name: 'King' },
    { species: 'Whale', name: 'Fail' }
];



for (var i = 0; i < animals.length; i++) {
    (function (i) {
        this.print()  {
            console.log(this)
            console.log('#' + i + '' + this.species + ':' + this.name)
        }
        // console.log(this)
        this.print()
    }).call(animals[i], i)
}

在call()函数中传入 animals[i],这样匿名函数内部的this就指向animals[i],在调用print函数时,this也会指向animals[i]

bind()函数配合setTimeout()

// 定义一个函数
function LateBloomer() {
    this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 定义一个原型函数
LateBloomer.prototype.bloom = function () {
    // 在一秒后调用实例的declare()函数,很关键的一句
    console.log(this)
    setTimeout(this.declare.bind(this), 1000);
};
// 定义原型上的declare()函数
LateBloomer.prototype.declare = function () {
    console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};
// 生成LateBloomer的实例
var flower = new LateBloomer();
console.log("🚀 ~ file: call,apply,bind.js ~ line 112 ~ flower", flower)


flower.bloom();  // 1秒后,调用declare()函数