R / Richie全部文章 ↑

前端 · 1 分钟阅读

JavaScript 中的类

目录


类和构造函数

类的定义

使用 class 关键字声明一个类:

class Person {
    name;
    constructor(name) {
        this.name = name 
    }
    introduceSelf() {
        console.log("My name is " + this.name)
    }
}

构造函数

构造函数用 constructor 关键字声明,执行流程:

  1. 创建新对象
  2. 绑定 this
  3. 执行构造函数代码
  4. 返回新对象

创建实例

const giles = new Person("Giles")
giles.introduceSelf()

省略构造函数

如果不需要特殊的初始化,可以省略构造函数:

class Animal {
    sleep() {
        console.log("I am sleeping")
    }
}
const spot = new Animal()
spot.sleep()

继承

基本语法

使用 extends 关键字实现继承:

class Professor extends Person {
    teaches

    constructor(name, teaches) {
        super(name)   
        this.teaches = teaches
    }

    introduceSelf(){
        console.log("My name is " + this.name + " and I teach " + this.teaches)
    }

    grade(paper) {
        const grade = Math.floor(Math.random() * 100)
        console.log(grade)
    }
}

super 关键字

super() 必须在访问 this 之前调用,用来执行父类的构造函数并传参。

创建子类实例

const walsh = new Professor("walsh", "math")
walsh.introduceSelf()
walsh.grade("my paper")

封装

私有属性

使用 # 前缀声明私有属性:

class Student extends Person {
    #year
    constructor(name, year) {
        super(name)
        this.#year = year
    }
    introduceSelf() {
        console.log("My name is " + this.name + " and I study " + this.#year)
    }

    canStudyArchey() {
        return this.#year > 1
    }
}

访问私有属性

const summers = new Student("summers", 2)
summers.introduceSelf()
summers.canStudyArchey()

summers.#year  // 错误:无法从类外部访问私有属性

私有方法

私有方法也用 # 前缀,只能在类内部调用:

class Example {
    somePublicMethod() {
        this.#somePrivateMethod()
    }

    #somePrivateMethod() {
        console.log("I am private")
    }
}

const myExample = new Example()

myExample.somePublicMethod()
myExample.#somePrivateMethod()  // 错误:无法从类外部访问私有方法

静态成员

静态方法

class MathUtils {
    static add(x, y) {
        return x + y;
    }
}

console.log(MathUtils.add(1, 2));  // 3

静态属性

class Config {
    static API_URL = "https://api.example.com";
    static VERSION = "1.0.0";
}

console.log(Config.API_URL);

静态成员属于类本身,不属于实例。