call,apply和bind

191 阅读1分钟

1. call

  • 改变this指向,this指向括号内第一个实参,括号内可接收无限个参数
  • 手写
Function.prototype.myCall = function(obj){
    if(obj===null||obj===undefined){
        obj = window
    }
    var args = []
    for(var i = 1;i<arguments.length;i++){
        args.push(arguments[i])
    }
    obj._b = this
    var res = eval("obj._b("+args.toString()+")")
    delete obj._b
    return res
}
//使用es6语法
Function.prototype.myCall = function(obj,...args){
    if(obj===null||obj===undefined){
        obj = window
    }
    obj._b = this
    var res =obj._b(...args)
    delete obj._b
    return res
}

2. apply

  • 改变this指向,this指向括号内第一个实参,第二个实参以数组的形式接收后续参数

3. bind

  • 返回一个新函数,这个函数被调用的时候才改变this指向
  • 手写
Function.prototype.myBind = function(obj,...args){
    if(obj===null||obj===undefined){
        obj = window
    }
    return (...args)=>{
        this.apply(obj,[...args])
    }
}