MST

星途 面试题库

面试题:JavaScript原型链与继承 - 继承模式实现与差异

请分别使用构造函数模式、原型模式、组合继承模式实现JavaScript的继承,并阐述每种继承模式的优缺点。
21.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

构造函数模式实现继承

function Parent(name) {
    this.name = name;
    this.sayName = function() {
        console.log(this.name);
    };
}

function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}

优点

  • 可以向父构造函数传递参数。
  • 每个实例都有自己的属性副本,相互独立,不会互相影响。

缺点

  • 方法都定义在构造函数中,每个实例都会创建相同的方法,造成内存浪费。
  • 无法复用父构造函数的原型方法。

原型模式实现继承

function Parent() {
    this.name = 'parent';
}

Parent.prototype.sayName = function() {
    console.log(this.name);
};

function Child() {
    this.age = 20;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

优点

  • 方法定义在原型上,所有实例共享,节省内存。

缺点

  • 实例共享原型上的属性和方法,如果修改原型上的引用类型属性,会影响所有实例。
  • 创建子类型实例时,无法向父类型构造函数传递参数。

组合继承模式实现继承

function Parent(name) {
    this.name = name;
    this.friends = ['John', 'Jane'];
}

Parent.prototype.sayName = function() {
    console.log(this.name);
};

function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

优点

  • 融合了构造函数模式和原型模式的优点,既可以向父构造函数传递参数,又能实现方法的复用。

缺点

  • 父构造函数会被调用两次,一次在Child构造函数中,一次在设置Child.prototype时,产生不必要的开销。