js常見原生方法重寫匯總(一)

Object.create

原理:創(chuàng)建對象,并且現(xiàn)有的對象來提供新創(chuàng)建的對象的proto

function objectCreate(fn){
  function Fn(){};
  Fn.prototype = fn;
  return new Fn();
}
new

原理:創(chuàng)建實例對象,方法執(zhí)行并讓this指向該實例對象,分析返回的結(jié)果。

function _new(fn,...args){
  let obj = Object.create(fn.prototype);
  let result = fn.call(obj,...args);
  if(typeof result==="object"&&result!==null){
    return result;
  }
  return obj;
}
instanceof

用于檢測構(gòu)造函數(shù)prototype 屬性是否出現(xiàn)在某個實例對象的原型鏈上。

function _instanceof(a,b){
  if(typeof a!=="object"||a===null){
    return false;
  }
  let pro = Object.getPrototypeOf(a);
  while(true){
    if(pro==null) return false;
    if(pro==b.prototype){
     return true;
    }
    pro = Object.getPrototypeOf(pro);
  }
}

console.log(_instanceof(new String("111"),String));//true
call,apply

都是改變this,不同的是傳參不同,call是一個一個傳,apply是傳一個數(shù)組。

Function.prototype._call=function(contxt,...args){
  if(typeof this!=="function"){
    throw Error("this is not function");
  }
  contxt = contxt||window;
  if(typeof contxt!=="object"||typeof contxt!=="function"){
    if(typeof contxt==="bigint"||typeof contxt==="symbol"){
      contxt = Object(contxt);
    }else{
      contxt = new contxt.constructor(contxt);
    }
  }
  let key = Symbol("key");
  contxt[key] = this;
  let result = contxt[key](...args);
  delete contxt[key];
  return result;
}

var a = '小紅';
let obj = {
  a:'小白',
  myName:function(){
    console.log(this.a);
  }
}

function myName(){
  console.log(this.a);
}
myName(); //小紅
myName._call(obj);//小白
bind

bind和call,apply都是改變this,不同的是bind不是立即執(zhí)行,屬于柯里化函數(shù)思想。

Function.prototype._bind = function(contxt,...args){
  return (...innerArgs)=>{
    this.call(contxt,...args.concat(...innerArgs));
  }
}
function myName(){
  console.log(this.a);
}
myName();
myName._bind(obj)();


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容