javascript如何实现继承_有哪些方法和模式【教程】

JavaScript继承无统一标准,核心是理解原型链和this绑定;ES6 class是语法糖,手动继承需用Object.create避免共享原型、修复constructor,并确保super()调用以初始化this。

JavaScript 实现继承没有单一“标准答案”,核心在于理解 prototype 链和 this 绑定机制。ES6 的 class 只是语法糖,底层仍依赖原型链;手动模拟继承时,稍有不慎就会丢失构造函数、覆盖原型或漏掉 super 调用。

为什么直接赋值 Child.prototype = Parent.prototype 不行

这会让子类和父类共享同一份原型对象,修改 Child.prototype 会意外影响 Parent.prototype,且 Child.prototype.constructor 指向错误(变成 Parent)。更严重的是,实例无法区分自己是哪个类构造出来的 —— instanceof 会失效。

正确做法是用 Object.create(Parent.prototype) 创建干净的委托链:

function Parent() 

{} Parent.prototype.say = function() { return 'hi'; }; function Child() {} Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; // 修复 constructor const c = new Child(); console.log(c instanceof Child); // true console.log(c instanceof Parent); // true console.log(c.say()); // 'hi'

ES6 class 继承中必须调用 super() 的原因

在子类构造函数里,this 在调用 super() 前是未初始化的(ReferenceError),这是 JS 引擎强制的限制。它确保父类的实例属性(如 this.name)被正确挂载,否则后续访问 this 会报错。

  • super() 必须在使用 this 前调用,哪怕只是读取 this.constructor
  • super(...args) 传参不等于自动转发:需显式写 super(name, age),不能只写 super()
  • 箭头函数里没有 super 绑定,不能在箭头函数中调用 super

组合继承 vs 寄生组合继承的区别在哪

组合继承(经典模式)会调用两次父类构造函数:一次在 Child.prototype = new Parent() 中,一次在 Child 构造函数内 Parent.call(this, ...)。前者只为建立原型链,却执行了父类初始化逻辑(比如发请求、改状态),造成冗余甚至副作用。

寄生组合继承只调用一次父类构造函数,也是目前公认最干净的手动继承模式:

function inheritPrototype(Child, Parent) {
  const prototype = Object.create(Parent.prototype);
  prototype.constructor = Child;
  Child.prototype = prototype;
}

function Parent(name) { this.name = name; }
function Child(name, age) {
  Parent.call(this, name); // 只这里调用
}
inheritPrototype(Child, Parent); // 原型链由 Object.create 建立

注意:Object.setPrototypeOf(Child.prototype, Parent.prototype) 功能等价但性能略差,且部分旧环境不支持。

extends 时静态方法和原型方法不会自动继承

static 方法默认不参与原型链查找,必须显式设置继承关系:

class Parent {
  static create() { return new this(); }
}
class Child extends Parent {}

Child.create(); // ✅ 正常工作 —— 因为 ES6 class 的 extends 会自动设置 Object.setPrototypeOf(Child, Parent)

// 但手动实现时不会:
function Parent() {}
Parent.staticMethod = () => {};
function Child() {}
Object.setPrototypeOf(Child, Parent); // 必须加这一行,否则 Child.staticMethod === undefined

同样,Child.prototype 上的方法不会自动出现在 Parent.prototype 上,反之亦然 —— 继承是单向的,别指望改子类原型能影响父类行为。

真正容易被忽略的是:所有继承模式都依赖正确的 constructor 指向和 instanceof 行为一致性。一旦 constructor 没修复,序列化、调试工具、第三方库(如 Vue 的响应式追踪)就可能出问题 —— 这些细节往往在线上运行很久才暴露。