apply、call、bind区别及实现

107 阅读1分钟

apply、call、bind区别及实现

相同点

都将修改this指向到context,为null时指向window

不同点

  • apply第二个参数接收一个参数数组
  • call接收多个参数
  • bind接收多个参数,并返回一个新函数

apply(context, args)

Function.prototype.apply1 = function (context, args) {
    context = (context === null || context === undefined) ? window : context
    context.__proto__.__this = this
    const ctxSelf = context.__this(...args)
    delete context.__proto__.__this
    return ctxSelf
}

call(context, arg1, arg2, arg3...)

Function.prototype.call1 = function (context, ...args) {
    context = (context === null || context === undefined) ? window : context
    context.__proto__.__this = this
    const ctxSelf = context.__this(...args)
    delete context.__proto__.__this
    return ctxSelf
}

bind(context, arg1, arg2, arg3...)

Function.prototype.bind1 = function (context, ...args1) {
    const _this = this
    return function (...args2) {
        return _this.apply1(context, [...args1, ...args2])
        // 或 return _this.call1(context, ...args1, ...args2)
    }
}

context 被冻结或是属性不可修改时也可完成功能