前囧(02篇)bind、call、apply 区别

193 阅读1分钟

call, apply, bind这三个方法都可以改变函数内部this指向。区别是call, apply是立即指向该函数,而bind是返回一个新的函数,用于下次调用

  • call 和 apply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同。
  • 除了第一个参数外,call 可以接收一个参数列表,apply 只接受一个参数数组
  • bind 和其他两个方法作用也是一致的,只是该方法会返回一个函数。并且我们可以通过 bind 实现柯里化
// bind
if (!Function.prototype.bind) {
    Function.prototype.bind = function() {
        let that = this
        let ctx = [].shift.apply(arguments)
        let args = [].slice.apply(arguments)

        // 返回函数
        return function() {
            that.apply(ctx, args.concat([].slice.apply(arguments)))
        }
    }
}
// call
if (!Function.prototype.call) {
    Function.prototype.call = function() {
        let [ctx, ...args] = arguments;
        ctx.fn = this || window
        let res = ctx.fn(...args)
        delete ctx.fn;
        return res
    }
}
// apply
if (!Function.prototype.apply) {
    Function.prototype.apply = function() {
        let [ctx, args] = arguments;
        ctx.fn = this || window
        let res = ctx.fn(...args)
        delete ctx.fn;
        return res
    }
}

关注我

关注即送,一起成长吧

  • 你不知道的JavaScript(上).pdf
  • 你不知道的JavaScript(中).pdf
  • 你不知道的JavaScript(下).pdf