ES6从入门到精通:类与继承

发布于:2025-07-04 ⋅ 阅读:(18) ⋅ 点赞:(0)

ES6 类的基本概念

ES6 引入了基于类的面向对象编程语法,通过 class 关键字定义类。类可以包含构造函数、方法和属性。

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}

const person = new Person('Alice');
person.greet(); // 输出: Hello, Alice!

类的继承

使用 extends 关键字实现继承,子类可以继承父类的属性和方法。

class Student extends Person {
  constructor(name, grade) {
    super(name); // 调用父类构造函数
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying in grade ${this.grade}.`);
  }
}

const student = new Student('Bob', 5);
student.greet(); // 输出: Hello, Bob!
student.study(); // 输出: Bob is studying in grade 5.

静态方法与属性

静态方法和属性属于类本身,而非实例。通过 static 关键字定义。

class MathHelper {
  static PI = 3.14159;

  static calculateArea(radius) {
    return this.PI * radius * radius;
  }
}

console.log(MathHelper.calculateArea(5)); // 输出: 78.53975

类的访问器

通过 getset 定义访问器属性,控制属性的读取和赋值行为。

class Temperature {
  constructor(celsius) {
    this._celsius = celsius;
  }

  get fahrenheit() {
    return this._celsius * 9 / 5 + 32;
  }

  set fahrenheit(value) {
    this._celsius = (value - 32) * 5 / 9;
  }
}

const temp = new Temperature(25);
console.log(temp.fahrenheit); // 输出: 77
temp.fahrenheit = 86;
console.log(temp._celsius);   // 输出: 30

类的私有字段

ES2022 引入了私有字段(Private Fields),通过在字段名前加 # 实现私有化。

class Counter {
  #count = 0;

  increment() {
    this.#count++;
  }

  getCount() {
    return this.#count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
// console.log(counter.#count);   // 报错: Private field '#count' must be declared in an enclosing class

类的检查与扩展

使用 instanceof 检查对象是否属于某个类,通过 Object.getPrototypeOf 获取原型链。

console.log(student instanceof Student); // true
console.log(student instanceof Person);  // true
console.log(Object.getPrototypeOf(student) === Student.prototype); // true

以上内容涵盖了 ES6 类的核心特性,包括定义、继承、静态成员、访问器、私有字段以及类型检查。


网站公告

今日签到

点亮在社区的每一天
去签到