Skip to content

实现 Function.prototype.apply()

Posted on:2021年7月7日 at 00:12

第一个参数是绑定的this,默认为window,第二个参数是数组或类数组


Function.prototype.apply = function (context = window, args) {
  if (typeof this !== "function") {
    throw new TypeError("Type Error");
  }
  const fn = Symbol("fn");
  context[fn] = this;

  const res = context[fn](...args);
  delete context[fn];
  return res;
};
原文转自:https://fe.ecool.fun/topic/c8245703-a177-4deb-a8be-24f73a3267b8