js类实现
JavaScript 类实现
JavaScript 中的类(Class)是 ES6 引入的语法糖,本质是基于原型继承的封装。以下是类的实现方式和常见用法。
基本类定义
使用 class 关键字定义类,构造函数通过 constructor 方法实现。

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
继承
通过 extends 实现继承,子类可通过 super 调用父类构造函数或方法。
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数
this.grade = grade;
}
study() {
return `${this.name} is studying in grade ${this.grade}`;
}
}
静态方法
使用 static 定义静态方法,可直接通过类名调用。

class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(2, 3)); // 输出: 5
Getter 和 Setter
通过 get 和 set 定义属性的访问器。
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
set width(value) {
if (value > 0) {
this._width = value;
}
}
}
私有字段
ES2022 引入的私有字段语法,以 # 开头。
class Counter {
#count = 0; // 私有字段
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
注意事项
- 类声明不会提升,必须先定义后使用。
- 类方法不可枚举(非类语法的方法是可枚举的)。
- 类内部默认启用严格模式。





