前端进阶必学:JavaScript Class 的正确打开方式,让你代码更清晰!

一、什么是 Class?

类是构造对象的蓝图,它定义了对象的属性和方法。在JavaScript中,类是通过class关键字来定义的,它的本质是一种语法糖,仍然是基于原型链的,class 内部的属性和方法最终都会添加到构造函数的 prototype 属性上。class 关键字提供了一种更清晰、更结构化的方式来定义对象和它们之间的关系。

二、Class 的基本语法:

class Person {
  // 构造函数
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // 方法
  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }

  // 静态方法
  static greet() {
    console.log("Hello!");
  }
}

// 创建实例
let person1 = new Person("Alice", 30);
person1.sayHello(); // 输出 "Hello, my name is Alice and I am 30 years old."

// 调用静态方法
Person.greet(); // 输出 "Hello!"

Class 的组成部分:

  • constructor 构造函数,用于创建和初始化对象。如果没有显式定义 constructor,JavaScript 会自动创建一个默认的构造函数。
  • 方法: 定义在 class 内部的函数,用于描述对象的行为。
  • 静态方法: 使用 static 关键字定义的方法,属于类本身,而不是类的实例。可以通过类名直接调用静态方法。

三、Class 的继承:

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

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

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

  // 重写父类的方法
  sayHello() {
    console.log(`Hello, my name is ${this.name}, I am ${this.age} years old, and I am studying ${this.major}.`);
  }
}

let student1 = new Student("Bob", 20, "Computer Science");
student1.sayHello(); // 输出 "Hello, my name is Bob, I am 20 years old, and I am studying Computer Science."
student1.study(); // 输出 "Bob is studying Computer Science."

继承的关键点:

  • extends 用于指定父类。
  • super() 用于调用父类的构造函数。必须在子类的构造函数中调用 super(),才能正确初始化父类的属性。
  • 方法重写 (Override): 子类可以定义与父类同名的方法,从而覆盖父类的方法。

四、Getter 和 Setter:

可以使用 getset 关键字定义属性的 getter 和 setter 方法,从而控制属性的访问和修改。

class Circle {
  constructor(radius) {
    this._radius = radius; // 使用 _radius 作为内部属性
  }

  get radius() {
    return this._radius;
  }

  set radius(value) {
    if (value <= 0) {
      throw new Error("Radius must be positive.");
    }
    this._radius = value;
  }

  get area() {
    return Math.PI * this._radius * this._radius;
  }
}

let circle1 = new Circle(5);
console.log(circle1.radius); // 输出 5
console.log(circle1.area); // 输出 78.53981633974483

circle1.radius = 10;
console.log(circle1.radius); // 输出 10
console.log(circle1.area); // 输出 314.1592653589793

// circle1.radius = -1; // 抛出错误 "Radius must be positive."

五、静态属性:

可以使用 static 关键字定义静态属性,静态属性属于类本身,而不是类的实例。

class Counter {
  static count = 0;

  constructor() {
    Counter.count++;
  }

  static getCount() {
    return Counter.count;
  }
}

let counter1 = new Counter();
let counter2 = new Counter();
console.log(Counter.getCount()); // 输出 2
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容