bmvpdxl / blog

博客
0 stars 0 forks source link

手写源码系列一(call,apply,bind) #5

Open bmvpdxl opened 5 years ago

bmvpdxl commented 5 years ago

最近看到一个手写源码系列,我也来凑个热闹,当做复习和总结了。

// call
Function.prototype.myCall = function(ctx, ...args) {
  if (ctx == undefined) {
    ctx = window;
  }

  const sys = Symbol();
  ctx[sys] = this;
  const res = ctx[sys](...args);
  delete ctx[sys];
  return res;
};

// apply
Function.prototype.myApply = function(ctx, args = []) {
  if (ctx == undefined) {
    ctx = window;
  }

  const sys = Symbol();
  ctx[sys] = this;
  const res = ctx[sys](...args);
  delete ctx[sys];
  return res;
};

// bind
Function.prototype.myBind = function(ctx, ...args) {
  if (ctx == undefined) {
    ctx = window;
  }

  const func = this;
  return function(...innerArgs) {
    const argumentList = args.concat(innerArgs);
    return func.apply(ctx, argumentList);
  };
};