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

其实上面的代码就相当于(改变函数中的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指调用该方法的函数,例如上面的例子如果是count函数调用,则this指的是count
  //这个代码的意思就是:_thisValue就是上面例子的obj,也就是obj.fn = count(){} 就是在该对象中增添该方法
  let result //用以接收返回值
  if(arr.length == 0) {
    _thisValue.fn() //没有传参数则直接调用该方法
  } else {
    let newAguiments = []
    for(let i = 0;i < arr.length;i++) {
      newAguiments.push('arr[' + i + ']') 
      //因为假如直接传arr[i]的话,如果传的参数是'你好',2,3,newAguiments就是['你好',2,3],
      //在eval中是eval('_thisValue.fn(你好,2,3)') 你好 这个字符串没有加双/单引号 可见 如果存在字符串这种情况的话就会报错
    }
    result = eval('_thisValue.fn(' + newAguiments + ')') //eval函数可执行字符串中的语句
  }
  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指调用该方法的函数,例如上面的例子如果是count函数调用,则this指的是count
  //这个代码的意思就是:_thisValue就是上面例子的obj,也就是obj.fn = count(){} 就是在该对象中增添该方法
  let result //用以接收返回值
  if(arr.length == 0) {
    result =  _thisValue.fn() //没有传参数则直接调用该方法
  } 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
}

你可能感兴趣的:(Function.prototype.apply())