← 返回完整题库
JavaScript困难

JavaScript 如何实现继承?

参考答案

ES5 方式

  1. 原型链继承:Child.prototype = new Parent()(共享引用属性、不能传参);
  2. 构造函数继承:Parent.call(this)(属性独立、方法不复用);
  3. 组合继承:两者结合(父构造调用两次);
  4. 寄生组合继承(最优):
function inherit(Child, Parent) {
  Child.prototype = Object.create(Parent.prototype);
  Child.prototype.constructor = Child;
  Object.setPrototypeOf(Child, Parent);
}
  1. Object.create(proto) 直接指定原型。

ES6 class

class Child extends Parent { constructor(...a) { super(...a); } method() { return super.method(); } }

本质仍是原型链继承,但有 super、不可直接调用、方法不可枚举、默认严格、可继承内置类。

要点:实例属性用构造函数/字段,共享方法放 prototype;静态属性通过 Object.setPrototypeOf 或 static。

本题来自 计算机知识面试题库,共 921 道题。