JS:手写call,apply&bind

76 阅读1分钟
//手写call,apply,bind
//原理:用传入的对象去调用当前的函数
Function.prototype.my_call = function(context){
  let ctx = context || window;
  ctx.fn = this;//this现在其实指向的是要调用的函数
  let args = Array.from(arguments).slice(1);//获取实参
  let res = arguments.length > 1 ? ctx.fn(...args) : ctx.fn();//调用函数并存储返回结果
  delete ctx.fn;//防止污染
  return res;
}

Function.prototype.my_apply = function(context){
  //原理与call相似 只需要改一下参数处理
  //apply函数的第二个参数是一个数组
  let ctx = context || window;
  ctx.fn = this;
  let res = arguments.length > 1 ? ctx.fn(...arguments[1]) : ctx.fn();
  delete ctx.fn;
  return res;
}

Function.prototype.my_bind = function(context){
  //原理:bing最终返回的是一个函数,而不是立刻调用,所以还要对返回参函数进行数处理
  let ctx = context || window
  ctx.fn = this
  let args = Array.from(arguments).slice(1)
  return function(){//返回一个函数 等待调用
    let allArgs = args.concat(Array.from(arguments));//连接所有参数 
    return allArgs.length > 0 ? ctx.fn(...allArgs) : ctx.fn()
  }
}