JavaScript 中的类
2025-02-17
类和构造函数
类的定义
使用 class 关键字声明一个类:
class Person {
name;
constructor(name) {
this.name = name
}
introduceSelf() {
console.log("My name is " + this.name)
}
}构造函数
构造函数使用 constructor 关键字声明,执行以下步骤:
- 创建新对象
- 绑定 this
- 执行构造函数代码
- 返回新对象
创建实例
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 关键字
- 必须在访问 this 之前调用 super()
- 用于调用父类构造函数
- 传递父类构造函数所需的参数
创建子类实例
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)
summer.introduceSelf()
summer.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);注意: 静态成员属于类本身,而不是类的实例。