call、apply、bind实现

1.语法

func.call(_this,arg1,arg2)
func.apply(_this,[arg1,arg2])
func.bind(_this,arg1,arg2)()

2.call、apply、bind实现

实现原理:

     都是Function.prototype上的方法

     第一个参数没传,指向global或window

     foo.func()  隐式调用this指向问题

function print(b,c){
      console.log(this.a,b,c)
}
// call实现
Function.prototype.myCall = function (){
  let [thisArr,...args] = [...arguments]
  if(!thisArr) thisArr = typeof window === 'undefined' ? global : window
  thisArr.func = this
  const result = thisArr.func(...args)
  delete thisArr.func
  return result
}
print.myCall({a:888},999,1000)

// apply实现
Function.prototype.myApply = function (thisArr,rest){
    if(!thisArr) thisArr = typeof window === 'undefined' ? global : window
    thisArr.func = this
    let result;
    if(rest){
          result = thisArr.func(...rest)
    }else{
          result = thisArr.func()
    }
    delete thisArr.func
    return result
}
print.myApply({a:888},[999,1000])

function doSomething(b){
      console.log(this.a+b)
}
// 实现bind
Function.prototype.myBind = function (){
    let [thisArr,...args] = [...arguments]
    if(!thisArr) thisArr = typeof window === 'undefined' ? global : window
    const func = this
    return function (){
           func.apply(thisArr,[...args,...arguments])
    }
}
const result = doSomething.myBind({a:2},3)()

  

posted @ 2021-08-18 16:10  卷叶小树  阅读(31)  评论(0编辑  收藏  举报