← 返回完整题库
ES6简单

es5 和 es6 使用 new 关键字实例化对象的流程是一样的吗?

参考答案

结论

不完全一样。两者都用 new 创建对象并绑定 this,但在继承(extends)场景下流程有本质差异:ES6 的 super() 改变了 this 的创建者。

ES5 的 new 流程

function Person(name) { this.name = name; }
function Child(name) { Person.call(this, name); }   // 借用父类构造器
Child.prototype = Object.create(Person.prototype);

new Child() 时:

  1. 创建一个空对象;
  2. 把该对象的 __proto__ 指向 Child.prototype;
  3. 以该对象为 this 执行 Child;
  4. 若构造器返回对象则返回它,否则返回该对象。

→ this 由 new 操作符创建,子类通过 call 借用父类初始化,原型链手动接。

ES6 的 new 流程

class Person { constructor(name) { this.name = name; } }
class Child extends Person { constructor(name) { super(name); } }

new Child() 时:

  1. 内部创建对象的是基类(Person)的构造器:super() 调用 [[Construct]] 生成 this;
  2. 子类构造器**没有自己的 this**,必须调用 super() 后才能用 this(否则 ReferenceError);
  3. 原型链由 extends 自动设置(Child.prototype.__proto__ === Person.prototype,且 Child.__proto__ === Person 支持静态继承);
  4. 返回值规则相同:返回对象则覆盖,否则用创建的 this。

关键差异

| 维度 | ES5 | ES6 class |
| --- | --- | --- |
| this 创建者 | new 操作符 | 父类构造器(super) |
| 必须 super() | 无此概念 | ✅ 子类构造器必须先调用 |
| 可否裸调用 | 可以(Person() 不报错) | ❌ 报 Class constructor cannot be invoked without 'new' |
| 原型链 | 手动 Object.create | 自动设置 |
| 静态继承 | 手动拷贝 | Child.__proto__ === Parent |
| new.target | 难以获取 | 原生支持 |
| 内置子类化(如继承 Array) | 有缺陷(length 等内部槽不生效) | 正确(super 创建的是真数组) |

为什么内置类继承是关键差异

ES5 的 new 先创建普通对象再改原型,无法给对象添加内置内部槽(如 Array 的 length、Date 的时间值),所以 class MyArr extends Array 在 ES5 模式下行为异常;ES6 由父类构造器创建对象,内部槽正确。

一句话

创建对象 + 绑定 this 的"结果"相似,但"谁创建 this、原型与静态链如何建立"不同:ES6 通过 super 把创建权交给父类,因此支持真正的内置类型继承,且强制 new 调用。

本题来自 计算机知识面试题库,共 921 道题。