通过手动实现来看call、apply、bind三者的区别

Function.prototype.mycall = function (context, ...args) {
    let cxt = context || window
    //确保唯一
    let fn = Symbol()
    //在cxt中添加方法,this是调用call的函数
    cxt[fn] = this
    //调用方法,记录结果
    const res = cxt[fn](...args)
    //在cxt中删去添加的方法
    delete cxt[fn]
    //返回结果
    return res
}

Function.prototype.myapply = function (context, args = []) {
    let cxt = context || window
    //确保唯一
    let fn = Symbol()
    //在cxt中添加方法,this是调用call的函数
    cxt[fn] = this
    //调用方法,记录结果
    const res = cxt[fn](...args)
    //在cxt中删去添加的方法
    delete cxt[fn]
    //返回结果
    return res
}

Function.prototype.mybind = function (context, ...args) {
    //表示当前函数
    const fn = this
    let newFn = function (...args2) {
        fn.apply(context, [...args, ...args2])
    }
    //让newFn继承目标函数的原型,保证能调用其原型上的方法
    newFn.prototype = Object.create(context.prototype)
    newFn.prototype.constructor = newFn
    //返回一个函数,在其中调用fn
    return newFn
}

三者的功能都是改变this指向

而区别主要在于:1.call和apply直接返回结果,而bind返回的是一个函数

                             2.call与apply参数输入为依次传参,而apply参数输入为参数数组

                             3.call与apply需要直接输入参数,而bind既可以直接输入,也可以在返回的函数                                  中输入

                             例:fn.bind(context,args)=fn.bind(context)(args)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值