into-piece / Step-By-Step

每天一题向前端架构师前进
4 stars 1 forks source link

手写call,apply,bind,new #11

Open into-piece opened 5 years ago

into-piece commented 5 years ago
function call (){
  let [ctx,...args] =  Array.from(arguments);
  ctx.fun = this || window;
  const res = args.length>0 ? ctx.fun(...args) : ctx.fun();
  delect ctx.fun;
  return res;
}

function apply () {
  let [ctx,args] =  Array.from(arguments);
  ctx.fn = this || window;
  const res = args.length>0?ctx.fn(args):ctx.fn();
  delect ctx.fn;
  return res;
}

function myNew(){
  let target = Object.create(null);
  let [constructor,...args] =  Array.from(arguments);
  target._proto_ = constructor.prototype
  const res = constructor.apply(target,args)
  if(res&&(typeof res == 'object'|| typeof res == 'function')){
    return res
  }
  return target
}