2021-01-14

this定義位置

JavaScript函數(shù)中的this不是在函數(shù)聲明的時候定義的,而是在函數(shù)調(diào)用(即運行)的時候定義的

原型鏈

簡單的回顧一下構(gòu)造函數(shù)、原型和實例的關(guān)系:每個構(gòu)造函數(shù)都有一個原型對象,原型對象都包含一個指向構(gòu)造函數(shù)的指針,而實例都包含一個指向原型對象的內(nèi)部指針。那么假如我們讓原型對象等于另一個類型的實例,結(jié)果會怎樣?顯然,此時的原型對象將包含一個指向另一個原型的指針,相應(yīng)地,另一個原型中也包含著一個指向另一個構(gòu)造函數(shù)的指針。假如另一個原型又是另一個類型的實例,那么上述關(guān)系依然成立。如此層層遞進,就構(gòu)成了實例與原型的鏈條。這就是所謂的原型鏈的基本概念。

new 作用

function Foo(name) {
  this.name = name
  return this
}

function InjectNew() {
 var obj = {}
 obj.__proto__ = Foo.prototype
  return  Foo.call(obj, name)
}

截屏2021-01-18 下午8.44.31.png
截屏2021-01-18 下午8.44.44.png

手動實現(xiàn)call、bind、apply

call

Function.prototype.myCall = function(thisArgs, ...args){
  if(thisArgs === null || thisArgs === undefined){
    thisArgs = window
  }else{
    thisArgs = Object(thisArgs)
  }
  
   const specialMethod = Symbol("anything"); 
  thisArgs[specialMethod] = this
  var result = thisArgs[specialMethod](args)
  delete thisArgs[specialMethod]
  return result
}

apply

Function.prototype.myApply = function(thisArg) {
  if(thisArg === null || thisArg === undefined){
    thisArg = window
  }else{
    thisArg = Object(thisArg)
 }

  const key = Symbol()
  thisArg[key] = this
  

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

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

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