【JS进阶】ES6 实现继承的方式

ES6 实现继承的方式

基本语法

javascript 复制代码
class Parent {
  constructor(name) {
    this.name = name;
    this.colors = ['red', 'blue'];
  }
  
  sayName() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 必须调用super(),且在使用this之前
    this.age = age;
  }
  
  sayAge() {
    console.log(this.age);
  }
}

const child1 = new Child('Tom', 10);
child1.sayName(); // "Tom"
child1.sayAge(); // 10
child1.colors.push('green');
console.log(child1.colors); // ['red', 'blue', 'green']

const child2 = new Child('Jerry', 8);
console.log(child2.colors); // ['red', 'blue'] (不共享引用属性)

关键点说明

  1. extends 关键字:用于声明类继承关系
  2. super 关键字
    • 在构造函数中:super() 调用父类构造函数,必须在访问 this 之前调用
    • 在方法中:super.method() 可以调用父类方法
  3. 静态方法继承:子类会继承父类的静态方法
  4. 原型方法继承:子类实例可以调用父类原型方法

与 ES5 继承的对比

特性 ES5 继承 ES6 class 继承
语法 复杂,需要手动处理原型链 简洁,使用 classextends
构造函数调用 需要手动调用父类构造函数 通过 super() 自动处理
静态方法继承 需要额外处理 自动继承
原型方法 需要手动设置原型链 自动继承
内置类继承 难以实现 可以继承内置类如 Array, Error 等

注意事项

  1. 必须调用 super() :在子类构造函数中,必须先调用 super() 才能使用 this

  2. super 的不同用法

    javascript 复制代码
    class Child extends Parent {
      constructor() {
        super(); // 调用父类构造函数
      }
      
      method() {
        super.parentMethod(); // 调用父类方法
      }
    }
  3. 可以继承内置类型

    javascript 复制代码
    class MyArray extends Array {
      // 可以扩展内置Array的功能
    }
  4. new.target:可以检测是通过哪个类被实例化的

底层实现

ES6 的 class 继承本质上是 ES5 寄生组合式继承的语法糖,Babel 转译后的代码类似于:

javascript 复制代码
function _inherits(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}

// 然后实现类似的继承逻辑
相关推荐
五月君_4 小时前
炸裂!Claude Opus 4.6 与 GPT-5.3 同日发布:前端人的“自动驾驶“时刻到了?
前端·gpt
Mr Xu_4 小时前
前端开发中CSS代码的优化与复用:从公共样式提取到CSS变量的最佳实践
前端·css
凡人叶枫4 小时前
C++中输入、输出和文件操作详解(Linux实战版)| 从基础到项目落地,避坑指南
linux·服务器·c语言·开发语言·c++
春日见5 小时前
车辆动力学:前后轮车轴
java·开发语言·驱动开发·docker·计算机外设
锐意无限5 小时前
Swift 扩展归纳--- UIView
开发语言·ios·swift
低代码布道师5 小时前
Next.js 16 全栈实战(一):从零打造“教培管家”系统——环境与脚手架搭建
开发语言·javascript·ecmascript
鹏北海-RemHusband5 小时前
从零到一:基于 micro-app 的企业级微前端模板完整实现指南
前端·微服务·架构
LYFlied5 小时前
AI大时代下前端跨端解决方案的现状与演进路径
前端·人工智能
念何架构之路5 小时前
Go进阶之panic
开发语言·后端·golang
光影少年5 小时前
AI 前端 / 高级前端
前端·人工智能·状态模式