手写 call、apply 及 bind 函数

之前在bind和apply以及call函数使用中详解总结过bindapply以及call函数的使用,下面手写一下三个函数。
一、首先call函数

Function.prototype.MyCall = function (thisArg, ...args) {
  let fn = this  //this指的是当前函数
  thisArg = (thisArg === undefined || thisArg === null) ? window : Object(thisArg)
  thisArg.fn = fn
  args = args || [] //如果arg不存在,就将其设置为[],方便结构
  let res = thisArg.fn(...args)
  delete thisArg.fn  //执行完之后就删除该对象上的属性
  return res
}

二、手写apply函数

Function.prototype.MyApply = function (obj, arg) {
  let fn = this //this表示函数
  // 如果要是obj为undefined或者null时,设置其为window,
  // 如果是基本数据类型,则将其设置为对象类型
  let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
  thisArg.fn = fn
  arg = arg || [] //如果arg不存在,则直接赋值为[]
  let res = thisArg.fn(...arg)
  delete thisArg.fn
  return res
}

三、手写bind函数

Function.prototype.MyBind = function(obj, ...args1) {
    let fn = this
    let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
    
    return function(...args2) {
      thisArg.fn = fn
      let args = [...args1, ...args2]
      let result = thisArg.fn(...args)
      delete thisArg.fn
      return result
    }
}
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值