JavaScript 中原型链中组合继承怎么理解
组合继承通过同时使用构造函数继承属性和原型链继承方法,解决了属性共享和函数复用问题。具体做法是在子类构造函数内部调用父类构造函数以获取独立副本,并将子类原型指向父类实例以建立原型链。

为什么需要组合继承而不是单独使用原型链或构造函数
单独使用原型链会导致引用类型属性被所有实例共享,而单独使用构造函数则无法实现方法的复用。组合继承结合了两者的优点,确保每个实例拥有独立的属性副本,同时共享原型上的方法。

function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name); // 第二次调用 Parent
this.age = age;
}
Child.prototype = new Parent(); // 第一次调用 Parent
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log(this.age);
};组合继承在原型链中的具体表现是什么
在原型链中,子类的原型对象是父类的一个实例,这意味着子类可以通过原型链访问到父类原型上的方法。同时,子类实例拥有自己的属性,这些属性是通过在子类构造函数中调用父类构造函数获得的。
立即学习“Java免费学习笔记(深入)”;
// 验证组合继承的原型链表现
const child1 = new Child('Alice', 5);
const child2 = new Child('Bob', 6);
console.log(child1 instanceof Child); // true
console.log(child1 instanceof Parent); // true
console.log(child1.colors === child2.colors); // false, 属性独立
console.log(child1.sayName === child2.sayName); // true, 方法共享


















