继承的方式4:组合继承的优化1(共享原型对象,不推荐)
面试速答(30 秒版 TL;DR)
- 目标:避免
Child.prototype = new Parent()导致的“父构造函数第二次执行”。 - 写法:
Child.prototype = Parent.prototype,让子类直接复用父类原型对象。 - 致命问题:父子类共享同一个原型对象,对子类原型的修改会污染父类原型,破坏封装与可维护性。
代码:看起来省事,实际上非常危险
function Parent() {}
Parent.prototype.say = function () {
return "parent";
};
function Child() {
Parent.call(this);
}
Child.prototype = Parent.prototype; // 省掉了一次 new Parent()
Child.prototype.constructor = Child; // 但这里会改到 Parent.prototype.constructor 也一起变了
Child.prototype.onlyChild = function () {
return "child";
};
const p = new Parent();
console.log(typeof p.onlyChild); // "function" (被污染了)
为什么会污染?
因为 Child.prototype 和 Parent.prototype 指向的是同一个对象。你在子类上“加方法/改 constructor”,本质是在改父类原型。
面试如何表达这个点(建议话术)
“这种优化确实避免了二次调用父构造函数,但会造成父子共享同一个 prototype 对象,子类扩展会影响父类,属于高风险写法。生产上更推荐用 Object.create(Parent.prototype) 做寄生组合继承。”
速记要点(可背诵)
Child.prototype = Parent.prototype省一次new Parent(),但会让父子共享原型对象,极易污染,通常不推荐。