手写代码call,apply,bind,new,constructor,instanceof hasPubProperty

call

//call()让函数执行,第一个参数让this的指向改成传进去的参数 后面的当参数传进函数里面。返回值为原函数的返回值 若是不传参数为window
Function.prototype.myCall=function myCall(context=window,...arg){
      
     let m=Symbol();
     context[m]=this;
     let res=context[m](...arg);
     delete context[m]//若是不删除,Function的原型上会有一个方法。
     return res;
}

复制代码

apply

//apply()让函数执行,第一个参数让函数内部的this的指向改成传进去的参数,第二个参数为数组,返回值为原函数的返回值,若是不传参数。默认为window 和[];
  Function.prototype.myApply=function myApply(context=window,...arg=[]){
      let m=Symbol();
      context[m]=this;
      let res=context[m](arg);
      delete context[m];
      return res;
      
  }

复制代码

bind

//bind()不让函数执行,第一个参数让函数内部的this的指向改成传进去的参数,第二个做为参数传进原函数中,返回一个新的函数,而且新的函数能够从新传值,加上上面第二个参数一块儿传入新函数中。
  Function.prototype.myBind=function myBind(context=window,...arg)
    return (...ary)=>{
        return this.apply(context,arg.concat(ary));
    }

复制代码

new

//new 函数执行,形参赋值,变量提高,生成一个堆内存 this指向这个堆内存
 代码从上到下执行  返回这个堆内存;
 function myNew(...arg){
     var obj={};
     var Constructor=arg.shift();
     obj.__proto__=Constructor.prototype;
     var res=Constructor.apply(obj,arg);
      return typeof res==="object"?res:obj
     return 
 }

复制代码

constructor

// 检测数据类型 是什么返回数据类型
 function type(temp){
    let str= temp.constructor.toString();
    return str.slice(9,str.indexOf("("));
 }


复制代码

instanceof

//instanceOf xxx instanceof xxx2  xxx 到基类原型上 有没有xxx2的原型
   function myInstance_Of(L,R){
   var r=R.prototype,
       l=L.__proto__
     while(true){
         if(L===null)return false;
         if(l===r) return true;
         l=L.__proto_;
     }
   }

复制代码

hasPubProperty

return temp in this && !this.hasOwnProperty(temp);
    
}



复制代码
相关文章
相关标签/搜索