Object.create可安全建立子类原型链,避免父构造函数执行副作用;需手动修复constructor指向子类,并配合Parent.call(this)继承实例属性,ES6 class底层亦采用此机制。

直接用 Object.create 设置子类原型,就能跳过构造函数中冗余的 new Parent() 调用,避免父类初始化副作用,同时保持原型链干净可读。
用 Object.create 连接原型链
传统方式常写 Child.prototype = new Parent(),但会执行父构造函数,可能触发不期望的初始化逻辑(比如发请求、改状态)。Object.create(Parent.prototype) 只创建一个空对象,并将其 __proto__ 指向 Parent.prototype,不调用构造函数,语义更准确。
- 写法简洁:直接指定原型对象,不依赖实例
- 避免副作用:父类构造函数不会被意外执行
- 便于后续扩展:返回的对象可自由添加方法,不影响原
Parent.prototype
必须手动修复 constructor 指针
使用 Object.create 后,新原型对象的 constructor 仍指向 Parent,需手动修正为 Child,否则 instance.constructor 会出错。
Child.prototype = Object.create(Parent.prototype);Child.prototype.constructor = Child;- 也可合并写成:
Object.defineProperty(Child.prototype, 'constructor', { value: Child, writable: true, configurable: true });
配合 call 实现属性继承
原型链只解决方法复用,实例属性仍需在子类构造函数中通过 Parent.call(this, ...) 显式继承。这是组合式继承的关键一步。
- 父类定义实例属性:
function Parent(name) { this.name = name; } - 子类中调用:
function Child(name, age) { Parent.call(this, name); this.age = age; } - 这样既复用了原型方法,又保证每个实例拥有独立属性
ES6 class 其实底层也这么干
class Child extends Parent 编译后或运行时,内部正是用类似 Object.setPrototypeOf(Child.prototype, Parent.prototype) 或 Object.create(Parent.prototype) 建立原型关系,并自动处理 constructor 和 super 调用。理解 Object.create 能帮你读懂 transpiler 输出和调试继承问题。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











