javascript怎样实现继承机制【教程】

现代JavaScript继承优先用class+extends,因其语义清晰且自动建立正确原型链、修复constructor;直接赋值Parent.prototype给Child.prototype会导致共享原型和constructor指向错误。

JavaScript 没有传统面向对象语言中的 class 继承关键字(早期),但可以通过原型链、Object.create()call/apply 和 ES6 的 class + extends 实现继承——现代项目中,**优先用 class + extends,但必须理解其底层仍是原型链**。

为什么直接用 Parent.prototype = Child.prototype 会出问题

这是初学者常见误区:试图“复制”父类原型。这样做会让父子构造函数共享同一份原型对象,导致修改子类原型时意外影响父类,且无法正确设置

constructor 指向。

  • 错误写法:Child.prototype = Parent.prototype → 两者原型引用同一对象
  • 正确做法是让 Child.prototype 原型指向 Parent.prototype,即建立原型链:Object.setPrototypeOf(Child.prototype, Parent.prototype) 或用 Object.create(Parent.prototype)
  • ES6 中 class Child extends Parent 自动完成这一步,并确保 Child.prototype.constructor === Child

super() 在构造函数里不是可选的

在子类 constructor 中,若定义了构造函数,就必须在使用 this 前调用 super();否则会报错 ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

  • super() 本质是调用父类构造函数,初始化 this 上的实例属性
  • 如果父类构造函数需要参数(如 super(name, age)),子类必须传入对应参数
  • 若子类没写 constructor,JS 会自动补上一个隐式构造函数并调用 super()

ES6 class 继承和原型链继承的性能与兼容性差异

class 是语法糖,最终仍编译为原型操作,但行为更严格、语义更清晰;而手动模拟继承容易遗漏关键步骤(如未修复 constructor)。

  • 兼容性:class 在 IE 完全不支持,需 Babel 转译;Object.create() 方式兼容到 IE9+
  • 性能:现代引擎对 class 有专门优化,实际差异极小,不必为这点性能放弃可读性
  • 静态方法继承:class Child extends Parent 会自动继承 Parent 的静态方法(通过 Child.__proto__ === Parent),手动方式需额外赋值:Child.method = Parent.method

真正容易被忽略的是:子类方法中调用 super.xxx() 并非简单访问父类原型,而是基于当前调用栈的 [[HomeObject]] 决定查找起点——这意味着它和 this 的绑定、方法是否被重新赋值都有关联,调试时别只盯着 prototype 链看。