手写call,apply,bind

改变this调用 指向第一个参数

原理:在指向对象里加上这个调用函数这个方法即可

    //手写call/apply
    Function.prototype.myCall = function(context,...args){
      context = context || window;
      context.fn = this;
      // const result =  context.fn(...args)//call
      const result =  context.fn([...args])//apply
      delete context.fn;
      return result;
    }
    const obj1 ={
      name:'zhangsan'
    }
    function fn(){
      console.log(this.name);
    }
    fn.myCall(null,1,2);
    fn.myCall(obj1,1,2);

手写bind 返回一个函数,传递多次参数 支持直接调用。new调用(this指向丢失)

    //手写bind
    Function.prototype.myBind = function(context,...args){
      const _this = this;
      return function func(...args1){
        if(this instanceof func){
          return new _this(...args,...args1)
        }else{
          return _this.call(context,...args,...args1)
        }
      }
    }
    const obj2 ={
      name:'mybind'
    }
    function fn(a,b){
      console.log(this.name,a,b);
    }
    const fn1=fn.myBind(obj2,1);
    fn1(2)//直接调用
    const fn2 = new fn1(2)//作为构造函数等待被调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值