手写apply/call/bind

Function.prototype.myCall = function(context) {
  if(typeof this !== 'function') {
    // 判断当前调用者是否为函数
    return
  }
  // 保存传入的this指向,这里会出现没有传入this指向的问题,那么that就是默认的window
  that = context || window
  // 保存当前调用的函数
  that.fn = this
  // 通过slice来截取传入的参数
  const args = [...arguments].slice(1)
  // 传入参数调用函数
  const result = that.fn(...args)
  // 删除掉fn属性
  delete that.fn
  // 返回结果
  return result
}
Function.prototype.myApply = function(context) {
  if(typeof this !== 'function') {
    // 判断当前调用者是否为函数
    return
  }
  // 保存传入的this指向
  that = context || window
  // 保存当前调用的函数
  that.fn = this
  let result
  // 这里开始判断传入的参数是否存在,此时参数是一个数组形式[thisArg,[传参]]
  // 那么如果arguments[1]即传参存在的时候,就是需要传参调用保存的函数
  // 如果不存在就直接调用函数
  if (arguments[1]) {
    result = that.fn(...arguments[1])
  } else {
    result = that.fn()
  }
  return result
}
Function.prototype.myBind = function(context) {
    if (typeof this !== 'function') {
        throw new TypeError('Error')
    }
    //返回一个绑定this的函数,这里我们需要保存this
    const _this = this
    const args = [...arguments].slice(1)
        //返回一个函数
    return function F() {
        //因为返回一个函数,我们可以new F()需要判断能当做构造函数吗
        if (this instanceof F) {
            return new _this(...args, ...arguments)
        }
        return _this.apply(context, args.concat(...arguments))
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值