手写apply,bind,call 方法

apply 和 call 和 bind 的区别,三个方法都是改变this 指向问题,bind 最大区别是返回一个新的函数,
apply 和 call 对于参数传入的区别:
①:函数.call(对象,arg1,arg2…)
②:函数.apply(对象,[arg1,arg2,…])

	// step1: 把函数挂在到目标对象上
	// step2: 执行函数
	// step3: 删除step1中挂到目标对象上的函数,把目标对象”完璧归赵”
	Function.prototype.myCall = function (context,...args) {
		  // content 是传入的上下文	 
		  const ctx = context || window
		  // 这里的this是值调用方法,把这个方法赋值给传入contenx上下文,然后再执行这个方法
		  ctx.func = this
		  ctx.func(...args)
		  //最后再这里删除该方法,否则对象的属性或者方法会越来越多
		  delete ctx.func
	  }



// apply 只是对于参数传入的不同
Function.prototype.myApply = function (context,...arr) {
  const ctx = context || window
  ctx.func = this 
  if(!arr) {
    ctx.func()
  }else{
    ctx.func(...arr)
  }
  delete ctx.func
}
// bind 多加一步,返回一个新的函数
Function.prototype.myBind = function (context,...args) {
  const ctx = context || window
  ctx.func = this
  return function(){
    ctx.func(...args)
    delete context.func
  }   
}

``

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值