实现call,apply,bind

221 阅读1分钟

apply.call.bind 都是为了改变函数运行时上下文(this指向)而存在的

call

Function.prototype.call = funciton(context){
  var cxt = context || window;
  // 将当前被调用的function定义在cxt.fucn上
  cxt.func = this;
  // 获取实参
  var args = [...arguments].slice(1);
  //  以对象调用形式调用func,此时this指向cxt
  var res  = argument.length > 1 ? cxt.func(...args):cxt.func();
  detele cxt.func
  return res

}

apply

Functions.portotype.apply = function(context) {
  var cxt = context || window;
  cxt.func =  this;
  // 注意apply的入参和call不一样
  var args = arguments[1]
  var res = args.length ? cxt.func(...args):cxt.func();
  delete cxt.func;
  return res
 
}

bind

Function.prototype.bind =  function(context){
  var cxt=context || window;
  cxt.func = this;
  var args  = [...arguments].splice(1);
  return  function(){
   //  bind函数的实参与返回绑定函数的实参合并
   var argsAll  = args.conact([...arrguments])
   return argsAll.length ? cxt.func(...argsAll) || cxt.func()
  }
}