Function.prototype.apply 实现方法

123 阅读1分钟

Function.prototype.apply_ = function (ctx, args = []) {

\

  // 避免上下文不传,缺省值为 window 全局对象

\

    ctx = ctx ? Object(ctx):window

\

    ctx.fn = this  

\

  // 将入参强行修改为数组类型,对于字符串类型,直接抛出异常

\

  if (typeof args === "string") {

\

    throw new TypeError("CreateListFromArrayLike called on non-object");

\

  }

\

  args = args?Array.from(args): [];

\

  // 创建一个唯一的 Symbol 避免对象属性重复

\

  //const uniqueKey = Symbol("fn");

\

  // 保存当前的 this,当前的 this 原来指向调用它的方法

\

  //ctx[uniqueKey] = this;

\

\

\

  // 对象调用保存的方法, 此时 this(原方法) 指向被修改为ctx

\

  const res = args.length > 0 ? ctx.fn(...args) : ctx.fn();

\

  // 删除对象的属性,减少内存占用

\

  delete ctx.fn;

\

  return res;

};

\