构造函数原型链继承通过修改子类的 prototype 指向父类实例来实现,而方法借用则是通过在子类构造函数内部使用 call 或 apply 调用父类构造函数。前者解决了方法复用问题,后者解决了引用类型属性共享和传参问题。

如何设置原型链实现方法复用
将子类的 prototype 设置为父类的一个新实例,即可让子类实例共享父类原型上的方法。这种方式避免了在每个实例上创建重复的方法,实现了代码复用。

function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
// 子类构造函数体
}
// 核心:原型链继承
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出: Parent
上述代码中,Child.prototype = new Parent() 是关键步骤。此时 child 实例可以通过原型链找到 sayName 方法。需要注意的是,这种方式的缺点是所有 Child 实例共享同一个 Parent 实例的属性,如果属性是引用类型(如数组),修改一个实例会影响其他实例。
如何通过方法借用解决属性共享问题
在子类构造函数内部调用父类构造函数,并使用 call 或 apply 改变 this 的指向。这样每个子类实例都会拥有自己独立的父类属性副本,解决了引用类型共享的问题。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
function Child(name, age) {
// 核心:方法借用
Parent.call(this, name);
this.age = age;
}
const child1 = new Child('Alice', 10);
const child2 = new Child('Bob', 12);
child1.colors.push('green');
console.log(child1.colors); // ['red', 'blue', 'green']
console.log(child2.colors); // ['red', 'blue']
在 Child 构造函数中,Parent.call(this, name) 执行了父类的初始化逻辑,并将 this 绑定到当前的 Child 实例上。因此,child1 和 child2 拥有各自独立的 colors 数组。结合原型链继承,通常采用组合继承的方式,即同时使用这两种技术,以兼顾方法复用和属性独立。
组合继承中子类原型指向父类原型的问题
在组合继承中,如果先使用 Parent.call(this) 再设置 Child.prototype = new Parent(),会导致父类构造函数被调用两次。第一次在子类构造函数体内,第二次在设置原型时。这不仅浪费性能,还会导致子类原型上的 constructor 属性指向父类,需要手动修正。
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); // 第一次调用
this.age = age;
}
Child.prototype = new Parent(); // 第二次调用
Child.prototype.constructor = Child; // 修正 constructor
const child = new Child('Alice', 10);
child.sayName(); // Alice
console.log(child instanceof Parent); // true
console.log(child instanceof Child); // true
虽然组合继承是经典模式,但现代开发中更推荐使用 ES6 的 class 和 extends 语法,它底层自动处理了原型链和构造函数的调用,代码更简洁且不易出错。例如 class Child extends Parent { constructor(name, age) { super(name); this.age = age; } } 能实现相同效果且无重复调用问题。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










