// 定义父类
function Parent(name) {
this.name = name;
}
Parent.prototype.showName = function() {
console.log(`Name: ${this.name}`);
};
// 定义子类
function Child(name, age) {
// 借用构造函数继承属性
Parent.call(this, name);
this.age = age;
}
// 寄生组合继承关键步骤:创建一个中间函数
function F() {}
// 将中间函数的原型指向父类的原型
F.prototype = Parent.prototype;
// 创建子类的原型,使用中间函数
Child.prototype = new F();
// 修正子类原型的constructor属性
Child.prototype.constructor = Child;
// 新增方法
Child.prototype.showAge = function() {
console.log(`Age: ${this.age}`);
};