MST

星途 面试题库

面试题:JavaScript中寄生组合继承模式的基本实现

请用JavaScript代码实现寄生组合继承模式,假设有一个父类`Parent`和一个子类`Child`,`Parent`有一个属性`name`和一个方法`showName`,`Child`继承`Parent`并新增一个属性`age`和方法`showAge`。要求清晰展示寄生组合继承的关键步骤。
11.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
// 定义父类
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}`);
};