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

一、什么是 Class?

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

二、Class 的基本语法:

javascript 复制代码
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 关键字可以实现类的继承。子类可以继承父类的属性和方法,并可以添加自己的属性和方法。

javascript 复制代码
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 方法,从而控制属性的访问和修改。

javascript 复制代码
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 关键字定义静态属性,静态属性属于类本身,而不是类的实例。

javascript 复制代码
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
相关推荐
qq_406176145 分钟前
吃透JS异步编程:从回调地狱到Promise/Async-Await全解析
服务器·开发语言·前端·javascript·php
幻云20108 分钟前
Python深度学习:筑基与实践
前端·javascript·vue.js·人工智能·python
@大迁世界9 分钟前
停止使用 innerHTML:3 种安全渲染 HTML 的替代方案
开发语言·前端·javascript·安全·html
缘木之鱼10 分钟前
CTFshow __Web应用安全与防护 第二章
前端·安全·渗透·ctf·ctfshow
沛沛老爹11 分钟前
从Web到AI:多模态Agent Skills生态系统实战(Java+Vue构建跨模态智能体)
java·前端·vue.js·人工智能·rag·企业转型
子非鱼92119 分钟前
Vue框架快速上手
前端·javascript·vue.js
winfredzhang20 分钟前
从零构建:基于 Node.js 与 ECharts 的量化交易策略模拟系统
前端·node.js·echarts·股票·策略
Hi_kenyon21 分钟前
JS中的export关键字
开发语言·javascript·vue.js
We་ct23 分钟前
LeetCode 380. O(1) 时间插入、删除和获取随机元素 题解
前端·算法·leetcode·typescript
不吃洋葱.44 分钟前
js主要内容
开发语言·javascript·ecmascript