# 手写 API

虽然我们知道这东西怎么用就足够了,但是呢,为了应付面试也好,就当充实自己也好,这里单开出一个目录来写写。

# call 的实现

这个东西的实现原理其实就是在传入的第一个参数上加一个fn这个fn就是调用 call 的那个function也就是下面代码中的getValue

Function.prototype.mcall = function(context) {
  if (typeof context === "object" || typeof context === "function") {
    context = context || window;
  } else {
    context = Object.create(null);
  }
  context.fn = this; // this 就是 getValue
  const args = [...arguments].slice(1);
  const result = context.fn(...args); // 调用getValue(...args)
  delete context.fn; // 用完了就删掉
  return result;
};

function getValue(bb, cc) {
  console.log(this, this.aa, bb, cc);
}

let obj = {
  aa: "hello world",
};
getValue.mcall(obj, "bb", "cc");

# apply 的实现

跟上面的call同样的道理实现apply也就很简单了

Function.prototype.mapply = function(context, args) {
  if (typeof context === "object" || typeof context === "function") {
    context = context || window;
  } else {
    context = Object.create(null);
  }
  context.fn = this;
  const result = context.fn(...args);
  delete context.fn;
  return result;
};

function getValue(bb, cc) {
  console.log(this.aa, bb, cc);
}

const obj = {
  aa: "hello world",
};
getValue.mapply(obj, ["bb", "cc"]);

# bind 实现

bind说法比较多,看这吧,反正都是自己写的。https://github.com/Mopecat/Daily-Mission-Board/issues/2