最规范的继承方式是寄生组合继承,它通过object.create(parent.prototype)继承原型方法、parent.call(this)继承实例属性,并修复constructor,兼顾属性隔离、方法复用与constructor正确性;es6 class extends是其语法封装,自动处理原型链与constructor,更简洁安全。

最规范的继承方式是寄生组合继承,它兼顾属性隔离、方法复用和 constructor 正确性,是目前工程实践中推荐的标准写法。
寄生组合继承(推荐标准写法)
它融合构造函数继承(解决实例属性共享问题)和原型链继承(复用原型方法),同时避免了组合继承中父类构造函数被调用两次的冗余。
- 用
Object.create(Parent.prototype)设置子类原型,不执行父类构造函数 - 在子类构造函数中用
Parent.call(this, ...args)初始化实例属性 - 手动修复
Child.prototype.constructor = Child
示例:
function Parent(name) {
this.name = name;
this.colors = ['red'];
}
Parent.prototype.sayName = function() { console.log(this.name); };
function Child(name, age) {
Parent.call(this, name); // ✅ 继承实例属性,各实例独立
this.age = age;
}
Child.prototype = Object.create(Parent.prototype); // ✅ 继承原型方法,不触发 Parent()
Child.prototype.constructor = Child; // ✅ 修复 constructor
const c1 = new Child('Alice', 25);
c1.colors.push('blue');
const c2 = new Child('Bob', 30);
console.log(c1.colors); // ['red', 'blue']
console.log(c2.colors); // ['red'] —— 不共享
console.log(c1.sayName()); // 'Alice' —— 方法可调用
ES6 class extends(现代项目首选)
语法简洁、语义清晰,底层仍是寄生组合继承的封装,但强制约束更安全。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 子类必须在
constructor中调用super(),否则报错 -
super()等价于Parent.call(this, ...args) - 原型链自动建立,
constructor自动修复,无需手动处理
示例:
class Parent {
constructor(name) {
this.name = name;
this.colors = ['red'];
}
sayName() { console.log(this.name); }
}
class Child extends Parent {
constructor(name, age) {
super(name); // ✅ 必须调用,完成实例初始化
this.age = age;
}
}
避免单独使用的两种方式
原型链继承:子类原型直接等于 new Parent(),会导致所有实例共享引用类型属性(如数组、对象),且无法向父类传参。
构造函数继承:只在子类中调用 Parent.call(this),虽能隔离属性,但无法继承原型上的方法,造成方法重复创建、无法复用。
关键细节不能漏
- 无论哪种方式,只要操作了
prototype,都需检查constructor是否指向正确构造函数 - 涉及引用类型属性(如
this.list = [])时,必须通过构造函数继承或实例化隔离,不能依赖原型共享 - ES6 class 中若省略
constructor,默认隐式调用super();一旦显式定义,就必须手动调用super()
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










