(面试)原生实现call,bind,apply改变this指向

(面试)原生实现call,bind,apply改变this指向

var obj={
      name:'卢本伟'
  }
 function func(){
   console.log(this.name)
 }
 func.call(obj)

我们都知道,this指向问题, 函数谁调用,this就指向调用者
我们实现的思路就可以是给函数上创建一个方法并且添加到函数都有的prototype上

Function.prototype.callcodewhy = function (target, ...arg) {
      //永远记着谁调用就指向谁
      target.fn = this
      // 主动调用传进来的形参,绑定this
      target.fn(...arg)
      // 使用完后删除
      delete target.fn(...arg)
    }

使用

func.callcodewhy(obj)

我们实现了一个call方法后,bind和apply都是大同小异
apply 和 call 的主要区别就在 apply是接收一个数组

Function.prototype.applycodewhy = function (target, arg=[]) {
      //接收数组
      if(arg && !arg instanceof Array){
      // 我们就可以告诉调用者传参是错误的
      throw('apply方法的形参必须是一个数组')
      }
      //永远记着谁调用就指向谁
      target.fn = this
      // 主动调用传进来的形参,绑定this
      target.fn(...arg)
      // 使用完后删除
      delete target.fn(...arg)
    }

bind方法的区别在于,它返回的是一个方法,需要再次调用,因此在开发中使用频率较高

Function.prototype.bindcodewhy = function (target, ...arg) {
    // 使用箭头函数,传递this
     return  (...arg2)=>{
      //拼接bind再次调用的参数
      let arg3=arg+arg2
       target.fn = this
      // 主动调用传进来的形参,绑定this
      target.fn(...arg3)
      // 使用完后删除
      delete target.fn(...arg3)   
      }
    }

使用

 let binds= func.bindcodewhy(obj)
 binds(1)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值