实现 call, apply, bind

Function.prototype.mycall = function (_this, ...parameter) {
  // 当前this指向当前函数,函数也是对象
  const fn = this

  // 判断传过来的_this是否有值,如果有就把值都改为object, 如果没有就指向window
  // 防止参数是null 或者 undefined
  _this = _this !== null && _this !== undefined ? Object(_this) : window

  // 给_this创建一个fn,将当前函数赋给_this
  _this.fn = fn

  // 调用_this.fn  这样在fn函数中this的指向就为_this相当于fn.cell({a: 1})
  // parameter 是获取当前函数中可能存在的所有型参, 然后解构,这样_this.fn中也有对应的参数
  const result = _this.fn(...parameter)

  delete _this.fn

  return result
}

function foo(sum1, sum2) {
   console.log(this)
   return sum1 + sum2
}

const result = c.mycall({a: 1}, 20, 20)
console.log(result)
Function.prototype.myapply = function (_this, parameter) {
  // 当前this指向当前函数,函数也是对象
  const fn = this

  // 判断传过来的_this是否有值,如果有就把值都改为object, 如果没有就指向window
  // 防止参数是null 或者 undefined
  _this = _this !== null && _this !== undefined ? Object(_this) : window

  // 给_this创建一个fn,将当前函数赋给_this
  _this.fn = fn

 // parameter 可能存在undefined的情况,也就是可能没有传入型参
 // 因为apply传参需要包裹在数组里,这和cell不一样,所以可能存在...undefined报错
 const newParameter = parameter ? parameter : []

 // 调用_this.fn  这样在fn函数中this的指向就为_this相当于fn.apply({a: 1})
 const result = _this.fn(...newParameter)

 delete _this.fn

 return result
}

function foo(sum1, sum2) {
   console.log(this)
   return sum1 + sum2
}

const result = c.myapply({a: 1}, [20, 20])
console.log(result)
Function.prototype.mybind = function (_this, ...parameter) {
   // 当前this指向当前函数,函数也是对象
   const fn = this

   // 判断传过来的_this是否有值,如果有就把值都改为object, 如果没有就指向window
   // 防止参数是null 或者 undefined
   _this = _this !== null && _this !== undefined ? Object(_this) : window

   // bind是通过 var a = b.bind() a()  这里的function bar相当于a
   // bind有一种特殊情况 var a = b.bind({}, 10) a(20)
   // 在上面这种情况下 需要将两次的参数都传给b:  b(10, 20)
   function bar(...arr) {
     // 给_this创建一个fn,将当前函数赋给_this
     _this.fn = fn
     // 将bind方法传入的参数和函数调用时传入的参数合并为一个数组
     const arrs = [...parameter, ...arr]
     // 调用_this.fn  这样在fn函数中this的指向就为_this相当于fn.bind({a: 1})
     // parameter 是获取当前函数中可能存在的所有型参, 然后解构,这样_this.fn中也有对应的参数
     const result = _this.fn(...arr)

     delete _this.fn

     return result
   }
   return bar
}


function foo(sum1, sum2, sum3) {
   console.log(this)
   return sum1 + sum2 + sum3
}
const newFoo = foo.bind({ key: 'hhh' }, 10, 20)
const result = newFoo(30)
console.log(result)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值