Function.prototype.apply()

語法

  • apply()主要用途是改變this的指向
  • 舉個例子
let obj = {
  name: 'Amy',
  age: 18
}

function conNAme() {
  console.log(this.name)
}
function count() {
  console.log(this.age + 1)
}
count.apply(obj) //19
conNAme.apply(obj) //Amy

其實上面的代碼就相當于(改變函數(shù)中的this指向,指向了obj):

let obj = {
  name: 'Amy',
  age: 18,
  count() {
    console.log(this.age + 1)
  },
  conNAme() {
    console.log(this.name)
  }
}
obj.count()
obj.conNAme()

手寫

Function.prototype.myApply = function(thisValue,arr = []) {
  let _thisValue = thisValue || window //當沒有傳this則默認是window調用該方法
  _thisValue.fn = this //這里的this指調用該方法的函數(shù),例如上面的例子如果是count函數(shù)調用,則this指的是count
  //這個代碼的意思就是:_thisValue就是上面例子的obj,也就是obj.fn = count(){} 就是在該對象中增添該方法
  let result //用以接收返回值
  if(arr.length == 0) {
    _thisValue.fn() //沒有傳參數(shù)則直接調用該方法
  } else {
    let newAguiments = []
    for(let i = 0;i < arr.length;i++) {
      newAguiments.push('arr[' + i + ']') 
      //因為假如直接傳arr[i]的話,如果傳的參數(shù)是'你好',2,3,newAguiments就是['你好',2,3],
      //在eval中是eval('_thisValue.fn(你好,2,3)') 你好 這個字符串沒有加雙/單引號 可見 如果存在字符串這種情況的話就會報錯
    }
    result = eval('_thisValue.fn(' + newAguiments + ')') //eval函數(shù)可執(zhí)行字符串中的語句
  }
  delete _thisValue.fn //刪除對象中的該方法因為不能改變原本的對象
  return result
}

let obj = {
  name: 'Amy',
  age: 18
}
function conNAme(a,b,c) {
  console.log(this.name),
console.log(a,b,c)
}
function count() {
  console.log(this.age + 1)
}
count.myApply(obj) //19
conNAme.myApply(obj,['xiaosi',34,55]) //Amy xiaosi 34 55

另外一個方法

Function.prototype.myApply = function(thisValue,arr = []) {
  let _thisValue = thisValue || window //當沒有傳this則默認是window調用該方法
  _thisValue.fn = this //這里的this指調用該方法的函數(shù),例如上面的例子如果是count函數(shù)調用,則this指的是count
  //這個代碼的意思就是:_thisValue就是上面例子的obj,也就是obj.fn = count(){} 就是在該對象中增添該方法
  let result //用以接收返回值
  if(arr.length == 0) {
    result =  _thisValue.fn() //沒有傳參數(shù)則直接調用該方法
  } else {
    result = _thisValue.fn(...arr)
  }
  delete _thisValue.fn //刪除對象中的該方法因為不能改變原本的對象
  return result
}

call()

function myCall(thisValue,prams) {
  let _thisValue = thisValue || window
  _thisValue.fn = this
  const res = _thisValue.fn(...prams)
  delete _thisValue.fn
  return res
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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