Skip to content

手写call、bind和apply

new

js
function objectFactory() {
  let constructor = arguments[0];
  let args = [...arguments].slice(1);

  if (typeof constructor != "function") throw Error("type error");

  const newObj = Object.create(constructor.prototype);
  const result = constructor.apply(newObj, args);

  return result && (typeof result == "object" || typeof result == "function")
    ? result
    : newObj;
}

call

js
Function.prototype.myCall = function (context) {
  if (typeof this !== "function") throw new Error("Please use Function");

  const args = Array.from(arguments).slice(1);
  let result = null;

  context = context ?? window;
  const fnKey = Symbol("fn");
  context[fnKey] = this;

  result = context[fnKey](...args);

  delete context[fnKey];
  return result;
};

apply

js
Function.prototype.myApply = function (context) {
  if (typeof this !== "function") throw new Error("Please use Function");

  const args = arguments[1] ?? [];
  let result = null;

  context = context ?? window;
  const fnKey = Symbol("fn");
  context[fnKey] = this;

  result = context[fnKey](...args);

  delete context[fnKey];
  return result;
};

bind

js
Function.prototype.myBind = function (context) {
  if (typeof this !== "function") throw new Error("Please use Function");

  const fn = this;
  var args = [...arguments].slice(1);

  return function result() {
    let result = null;
    return fn.apply(
      this instanceof result ? this : context,
      args.concat(...arguments)
    );
  };
};

备案号:闽ICP备2024028309号-1