JavaScript 原型链继承导致属性共享怎么解决
使用构造函数模式结合 object.create() 可以彻底解决原型链继承导致的引用类型属性共享问题。核心做法是在子类的构造函数中调用父类构造函数,将父类的实例属性绑定到当前实例上,同时通过 object.create(parent.prototype) 建立正确的原型链,从而确保每个实例都拥有独立的属性副本。

为什么直接赋值原型会导致数据污染
直接将父类实例赋值给子类原型时,所有子类实例共享同一个原型对象。如果该对象包含数组或对象等引用类型属性,修改其中一个实例的属性会直接影响其他实例的数据。

function Parent() {
this.name = 'Parent';
this.arr = [1, 2];
}
function Child() {
this.type = 'Child';
}
// 错误做法:直接赋值实例
Child.prototype = new Parent();
const c1 = new Child();
const c2 = new Child();
c1.arr.push(3);
console.log(c2.arr); // 输出: [1, 2, 3] - 数据被污染
组合继承的具体实现方式
组合继承通过构造函数借用和原型链设置相结合的方式,既保证了实例属性的独立性,又实现了方法的复用。在子类构造函数内部调用 Parent.call(this) 初始化属性,并设置原型指向父类原型的新实例。

function Parent() {
this.name = 'Parent';
this.arr = [1, 2];
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
// 第二次调用 Parent 构造函数
Parent.call(this);
this.age = 29;
}
// 第一次调用 Parent 构造函数
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const c1 = new Child();
const c2 = new Child();
c1.arr.push(3);
console.log(c2.arr); // 输出: [1, 2] - 数据独立
console.log(c1 instanceof Child); // true
console.log(c1 instanceof Parent); // true
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











