call、apply、bind

三者的对比

call、apply与bind都是用来改变this指向的。

call与apply返回结果为函数调用结果,bind返回结果为新的函数,还需要重新调用

let obj = {
    age: 18,
    getAge: function () {
        return this.age
    }
}
let obj2 = {
    age: 16
}

console.log(obj.getAge())   //18
console.log(obj.getAge.call(obj2))  //16
console.log(obj.getAge.apply(obj2)) //16
console.log(obj.getAge.bind(obj2)())    //16(多一层调用)

call、apply、bind第一个参数均为this指向对象。之后的参数call与bind都是依次传入,apply以数组的方式传入

let obj = {
    age: 18,
    getAge: function (num1, num2) {
        return this.age + num1 + num2
    }
}
let obj2 = {
    age: 16
}

console.log(obj.getAge.call(obj2, 1, 2))  //19
console.log(obj.getAge.bind(obj2, 1, 2)())    //19
console.log(obj.getAge.apply(obj2, [1, 2])) //19    后面的参数以数组的形式传递进去

bind的返回结果也可传入参数,会与bind函数的参数一起传入,如

let obj = {
    age: 18,
    getAge: function (num1, num2) {
        return this.age + num1 + num2
    }
}
let obj2 = {
    age: 16
}

console.log(obj.getAge.bind(obj2, 1)(2))    //19

封装bind

Function.prototype.myBind = function (context, ...args) {
    return (...innerArgs) => {
        //innerArgs为bind函数返回结果即新函数中传入的参数,应与bind函数中传入的参数合并
        var finalArgs = args.concat(innerArgs)
        return this.apply(context, finalArgs)
    }
}

 

posted @ 2021-02-16 14:48  懒懒同学不懒  阅读(213)  评论(0编辑  收藏  举报