js 实现类
实现类的基本语法
在 JavaScript 中,可以通过 class 关键字定义类。类包含构造函数、方法和属性。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person('Alice', 25);
person.greet(); // 输出: Hello, my name is Alice
类的继承
使用 extends 关键字实现类的继承,子类可以调用父类的构造函数和方法。

class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}`);
}
}
const student = new Student('Bob', 18, 12);
student.greet(); // 输出: Hello, my name is Bob
student.study(); // 输出: Bob is studying in grade 12
静态方法
静态方法属于类本身,而不是类的实例。通过 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;
}
}
}
const rect = new Rectangle(10, 20);
console.log(rect.area); // 输出: 200
rect.width = 15;
console.log(rect.area); // 输出: 300
私有字段
通过 # 前缀定义私有字段,只能在类内部访问。
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
// console.log(counter.#count); // 报错: Private field '#count' must be declared in an enclosing class
类表达式
类可以通过表达式形式定义,类似于函数表达式。
const Animal = class {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise`);
}
};
const animal = new Animal('Dog');
animal.speak(); // 输出: Dog makes a noise
类的注意事项
- 类声明不会被提升,必须在定义后使用。
- 类的方法默认是不可枚举的。
- 类内部默认启用严格模式。
- 类的所有方法都定义在原型上,实例共享方法。






