罗罗编程学习记录
本页内容 展开查看

03.10.4 手写 bind、call、apply、new、instanceof、Object.create

所属:全栈开发面试题库 / 03 前端基础与 Web 开发 / 03.10 前端手写实现

覆盖范围

  • Function.prototype.call / apply:立即调用,this 绑定
  • Function.prototype.bind:延迟绑定 + 部分参数
  • new 运算符:构造函数 + 原型链
  • instanceof:原型链查找
  • Object.create:原型继承

高频题速览

编号 题目 难度 频率
03.10.4-001 手写 Function.prototype.call 基础 ★★★★★
03.10.4-002 手写 Function.prototype.apply 基础 ★★★★
03.10.4-003 手写 Function.prototype.bind 并处理 new 调用 高级 ★★★★★
03.10.4-004 手写 new 运算符 进阶 ★★★★★
03.10.4-005 手写 instanceof 进阶 ★★★★
03.10.4-006 手写 Object.create 基础 ★★★
03.10.4-007 bind 后作为构造函数时 this 如何处理 高级 ★★★★
03.10.4-008 call 与 apply 的性能差异 进阶 ★★★

03.10.4-001 手写 Function.prototype.call

一句话结论

call 把函数作为指定对象的临时属性调用,传入展开参数,调用后删除临时属性,返回函数执行结果。

概念解释

  • thisArg:函数运行时的 this。
  • 参数列表:逐个传入。

原理流程

  1. 在 thisArg 上挂一个临时唯一属性保存原函数。
  2. 调用 thisArg[tempKey](...args)。
  3. 删除临时属性,返回结果。

代码 / 示例

Function.prototype.myCall = function (thisArg, ...args) {
  const ctx = thisArg == null ? globalThis : Object(thisArg);
  const key = Symbol("fn");
  ctx[key] = this;
  const result = ctx[key](...args);
  delete ctx[key];
  return result;
};

常见误区

  • 误区:thisArg 为 null 时 this 是 window;正解:严格模式下是 undefined,非严格模式是全局对象。
  • 误区:直接赋值到 thisArg 会污染原对象;正解:用 Symbol 或随机 key 避免冲突。

追问

  • Q:如何不挂临时属性? A:用 Reflect.apply 或直接 this.apply(thisArg, args),但手写版本用挂属性法。
  • Q:原始值 thisArg 怎么办? A:Object(thisArg) 装箱成对象。

03.10.4-002 手写 Function.prototype.apply

一句话结论

apply 与 call 行为相同,但参数是数组或类数组对象。

概念解释

  • 参数:数组/类数组。
  • 与 call 区别:参数传递形式。

原理流程

  1. 与 call 相同,但把参数数组展开。

代码 / 示例

Function.prototype.myApply = function (thisArg, args = []) {
  const ctx = thisArg == null ? globalThis : Object(thisArg);
  const key = Symbol("fn");
  ctx[key] = this;
  const result = ctx[key](...args);
  delete ctx[key];
  return result;
};

常见误区

  • 误区:apply 第二参数必须是数组;正解:类数组对象(如 arguments)也可,需要先展开。
  • 误区:Math.max.apply(null, arr) 已过时;正解:现代用 Math.max(...arr),但超长数组展开会爆栈,apply 仍有用。

追问

  • Q:超长数组求最大值怎么办? A:分块或循环,apply 也会受栈限制。
  • Q:apply 与 call 性能差异? A:微小,现代引擎已优化。

03.10.4-003 手写 Function.prototype.bind 并处理 new 调用

一句话结论

bind 返回一个新函数,永久绑定 this 与前置参数;当新函数被 new 调用时,忽略绑定的 this,按构造函数初始化对象,并继承原函数的原型。

概念解释

  • 绑定 this:bind 第一个参数。
  • 部分参数:bind 后传入的参数前置。
  • new 调用:忽略绑定 this,this 指向新实例。

原理流程

  1. 返回 fBound 函数。
  2. fBound 内部判断 new.target 或 this instanceof fBound。
  3. 若是构造调用,用原函数 apply 到新对象。
  4. 否则用绑定的 this。

代码 / 示例

Function.prototype.myBind = function (thisArg, ...preset) {
  const fn = this;
  function fBound(...args) {
    const isNew = new.target || this instanceof fBound;
    return fn.apply(isNew ? this : thisArg, [...preset, ...args]);
  }
  fBound.prototype = Object.create(fn.prototype);
  fBound.prototype.constructor = fBound;
  return fBound;
};

常见误区

  • 误区:bind 后 new 仍用绑定的 this;正解:规范规定 new 忽略绑定 this,this 指向新实例。
  • 误区:bind 后函数的 prototype 丢失;正解:要手动把 fBound.prototype 链到原函数 prototype,否则 instanceof 失效。

追问

  • Q:为什么要 fBound.prototype = Object.create(fn.prototype)? A:保证 new Bound() 出来的实例能通过 instanceof Original。
  • Q:bind 可以多次 bind 吗? A:第一次之后 this 被锁死,后续 bind 的 this 无效。

03.10.4-004 手写 new 运算符

一句话结论

new 创建一个空对象,其 __proto__ 指向构造函数 prototype,把构造函数 this 绑定到该对象执行,若构造函数返回对象则用该对象,否则返回新对象。

概念解释

  • 新对象:内部 [[Prototype]] 指向构造函数 prototype。
  • 返回值:若构造函数返回对象则覆盖新对象。

原理流程

  1. 创建空对象 obj。
  2. 设置 obj.proto = Constructor.prototype。
  3. 调用 Constructor.apply(obj, args)。
  4. 若返回值是对象则返回,否则返回 obj。

代码 / 示例

function myNew(Constructor, ...args) {
  const obj = Object.create(Constructor.prototype);
  const ret = Constructor.apply(obj, args);
  return ret instanceof Object ? ret : obj;
}

常见误区

  • 误区:构造函数返回基本类型会被忽略;正解:是的,基本类型不覆盖新对象。
  • 误区:new.target 可以在手写 new 中模拟;正解:用 new.target 检测,或用 Object.setPrototypeOf 配合 Reflect.construct。

追问

  • Q:Reflect.construct 与手写 new 区别? A:Reflect.construct 可以指定 new.target,更灵活。
  • Q:箭头函数能 new 吗? A:不能,箭头函数没有 prototype 与 this。

03.10.4-005 手写 instanceof

一句话结论

instanceof 沿着对象的原型链查找,直到找到构造函数的 prototype 或到达 null。

概念解释

  • 原型链:obj.proto.proto...
  • 右操作数:必须是函数,其 prototype 作为查找目标。

原理流程

  1. 取 left 对象的原型。
  2. 不断向上查找,直到等于 right.prototype 或 null。

代码 / 示例

function myInstanceof(left, right) {
  if (left === null || typeof left !== "object") return false;
  let proto = Object.getPrototypeOf(left);
  while (proto) {
    if (proto === right.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

常见误区

  • 误区:instanceof 判断类型;正解:判断原型链,跨 realm 时(iframe)会失效。
  • 误区:原始值 instanceof 永远 false;正解:是的,原始值不是对象。

追问

  • Q:Symbol.hasInstance 是什么? A:自定义 instanceof 行为的钩子。
  • Q:如何判断跨 realm 数组? A:用 Array.isArray 或 toString。

03.10.4-006 手写 Object.create

一句话结论

Object.create 创建一个新对象,其 __proto__ 指向指定原型对象,可同时传入属性描述符。

概念解释

  • 原型继承:新对象继承指定原型。
  • 属性描述符:第二参数与 Object.defineProperties 一致。

原理流程

  1. 创建空对象。
  2. 设置其原型为指定 proto。
  3. 若传入描述符则定义属性。

代码 / 示例

function myCreate(proto, properties) {
  function F() {}
  F.prototype = proto;
  const obj = new F();
  if (properties) Object.defineProperties(obj, properties);
  return obj;
}

常见误区

  • 误区:Object.create(null) 是空对象;正解:它没有原型,toString 等方法都没有,适合做字典。
  • 误区:F.prototype = proto 后 new F() 共享原型;正解:这正是原型继承的核心。

追问

  • Q:Object.create(null) 与 {} 区别? A:无原型,不会被 hasOwnProperty 污染,适合做 Map 替代。
  • Q:实现 class 继承的关键? A:Object.setPrototypeOf(Son.prototype, Parent.prototype) 与 Object.setPrototypeOf(Son, Parent)。

03.10.4-007 bind 后作为构造函数时 this 如何处理

一句话结论

bind 返回的函数被 new 调用时,忽略绑定的 this,新对象的原型同时继承原函数与绑定函数的 prototype;这是规范规定的,为了兼容 bind 后的构造函数使用。

概念解释

  • new.target:new 表达式的目标函数。
  • 原型继承:fBound.prototype = Object.create(fn.prototype)。

原理流程

  1. 检测 new.target。
  2. 若为构造调用,this 指向新实例。
  3. 调用原函数 apply 到新实例。

代码 / 示例

function Person(name) {
  this.name = name;
}
const BPerson = Person.bind({ foo: 1 });
const p = new BPerson("ann");
console.log(p.name); // "ann"
console.log(p instanceof Person); // true

常见误区

  • 误区:bind 后 new 会用绑定的 this;正解:不会,绑定的 this 被忽略。
  • 误区:bind 后 instanceof 失效;正解:只要正确设置 prototype 链,instanceof 仍可用。

追问

  • Q:为什么规范这样设计? A:避免 bind 用于事件代理后无法用作构造函数。
  • Q:手写时如何检测 new? A:this instanceof fBound 或 new.target。

03.10.4-008 call 与 apply 的性能差异

一句话结论

现代 V8/JavaScriptCore 已对 call/apply 高度优化,性能差异可忽略;旧版本中 apply 展开数组有微小开销,超长参数数组会触发栈溢出。

概念解释

  • 展开开销:call 直接传参,apply 接收数组。
  • 栈限制:函数参数数量有上限(通常 65536)。

原理流程

  1. call 与 apply 内部都做 this 绑定。
  2. apply 需要把数组展开为参数列表。

代码 / 示例

const arr = new Array(200000);
Math.max.apply(null, arr); // 可能 RangeError

常见误区

  • 误区:call 永远比 apply 快;正解:现代引擎两者几乎等价。
  • 误区:apply 能处理任意长数组;正解:超出栈限制会抛 RangeError,超长用循环或分块。

追问

  • Q:如何替代 apply? A:fn.apply(ctx, arr) 等价于 fn.call(ctx, ...arr),超长用循环。
  • Q:Reflect.apply 有什么优势? A:明确接收 this 与参数数组,语义清晰。

待整理清单

  • [ ] 手写 Reflect.apply 与 Reflect.construct
  • [ ] 手写 Object.defineProperty 与响应式劫持
  • [ ] 手写 class 继承内部原理

关联与延伸

  • 与 03.2.1.4 this 与函数绑定配合阅读,本节聚焦手写实现。
  • new 与 bind 的组合行为是面试高频追问点,需重点掌握 fBound.prototype 链。
  • 现代浏览器已原生实现这些方法,手写目的是理解机制而非生产使用。