通过 object.create 将子类的原型对象指向父类实例,并修正 constructor 属性来实现。具体做法是在子类构造函数内部调用 parent.call(this, ...) 以继承实例属性,随后使用 child.prototype = object.create(parent.prototype) 建立原型链,最后手动设置 child.prototype.constructor = child 修复断裂的引用。

如何正确设置子类原型以继承父类方法
将 Child.prototype 设置为 Object.create(Parent.prototype) 的结果。这样做会在子类和父类之间建立一条干净的原型链,确保子类实例可以访问父类原型上的方法,同时避免直接赋值导致原型对象被覆盖的问题。

function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
return this.age;
};
const child = new Child('Alice', 10);
console.log(child.sayName()); // Alice
console.log(child.sayAge()); // 10
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // true
运行上述代码,child 实例能够正确调用 sayName 和 sayAge 方法。instanceof 检查返回 true,证明原型链连接正常。constructor 属性被修正后,child.constructor 指向 Child 而非 Parent。
为什么必须手动修正 constructor 属性
因为 Object.create 创建的对象默认没有 constructor 属性,或者该属性指向的是 Object。如果不手动修正,Child.prototype.constructor 会丢失对 Child 构造函数的引用,导致通过 constructor 判断实例类型或进行克隆时出现错误。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

// 修正前的状态 console.log(Child.prototype.constructor === Parent); // true (错误) // 修正后的状态 Child.prototype.constructor = Child; console.log(Child.prototype.constructor === Child); // true (正确)
在修正前,Child.prototype.constructor 实际上指向 Parent,这是因为 Object.create 生成的对象继承了 Parent.prototype 上的 constructor。修正后,它明确指向 Child,保证了类型识别的准确性。
子类实例是否共享父类原型上的引用类型属性
不会共享。因为原型链继承只复制了方法的引用,而每个子类实例在通过 Parent.call(this) 初始化时,都会获得自己独立的实例属性。如果父类原型上有引用类型属性,所有子类实例会共享该引用,但通常我们建议将实例属性放在构造函数中定义以避免此问题。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










