使用 object.create 将父类原型赋值给子类原型,并通过 call 在子类构造函数中调用父类构造函数以继承实例属性。这样既实现了原型链上的方法共享,又保证了每个实例拥有独立的属性数据。

如何正确设置子类的原型链
通过 Child.prototype = Object.create(Parent.prototype) 建立原型链接,并修正 constructor 指向。这确保了子类实例可以访问父类定义在原型上的方法,同时保持原型链的完整性。

function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log('My name is ' + this.name);
};
function Child(name, age) {
Parent.call(this, name); // 继承实例属性
this.age = age;
}
// 核心:设置原型链
Child.prototype = Object.create(Parent.prototype);
// 修复 constructor 指向
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log('I am ' + this.age + ' years old');
};
var child = new Child('Alice', 10);
child.sayName(); // My name is Alice
child.sayAge(); // I am 10 years old
运行上述代码,child 实例成功调用了来自父类原型的 sayName 方法和子类原型的 sayAge 方法。控制台输出显示名称和年龄均正确获取,验证了原型链设置的正确性。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
为什么需要手动修正 constructor 属性
在使用 Object.create 替换原型后,新原型的 constructor 属性会指向父类构造函数。如果不手动将其重置为子类构造函数,会导致通过 instance.constructor 检查时出现类型误判,影响基于构造函数的类型判断逻辑。

// 接上文代码 console.log(child.constructor === Child); // false (未修正前) console.log(child.constructor === Parent); // true (未修正前) // 执行修正后 console.log(child.constructor === Child); // true
修正前,child.constructor 指向 Parent,这意味着如果代码中有 if (obj.constructor === Child) 的判断,将会失败。修正后,constructor 重新指向 Child,恢复了正确的类型标识。这是传统构造函数继承模式中容易被忽视但至关重要的一步。
子类实例是否拥有父类的私有变量
子类实例不直接拥有父类构造函数中定义的私有变量(如闭包中的变量),但通过 Parent.call(this, ...) 继承的是父类构造函数内通过 this 挂载的属性。这些属性成为子类实例自身的属性,而非原型属性。
function Parent() {
var privateVar = 'secret'; // 私有变量
this.publicVar = 'public'; // 实例属性
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var c = new Child();
console.log(c.publicVar); // 'public'
console.log(c.privateVar); // undefined
测试结果表明,c.publicVar 可以被访问,因为它是通过 call 绑定到实例上的。而 privateVar 由于作用域限制,在子类实例中不可见。这证实了构造函数继承仅能传递实例属性,无法传递真正的私有成员。

















