手写call,apply与bind(二)

138 阅读1分钟

bind

Function.prototype.myBind = function(ctx){
      let self = this;
      let args1 = [...arguments].slice(1)
      //最关键就是这步,里面包含了一个函数的调用就是self.apply!!被当做构造函数
      //当使用new的时候,就是new vBound,vBound里面的this会instance of vBound
      //因此做个三元判断,如果为真的话,那么apply就再实例下面执行这个函数
      //注意new构造的继承问题要修改一下
      function vBound(){
        let args2 = [...arguments]
        return self.apply(this instanceof vBound ? this : ctx,args1.concat(args2))
      }
      function f() {}
      f.prototype = this.prototype;
      vBound.prototype = new f()
      //相等
      //为了不让修改vBound的prototype也修改this.prototype
      //vBound.prototype = Object.create(this.prototype)

      return vBound
    }