js实现class
实现类的基本语法
JavaScript 中使用 class 关键字定义类,通过 constructor 方法初始化实例属性。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
const person = new Person('Alice', 25);
console.log(person.greet()); // 输出: Hello, my name is Alice
继承与扩展
使用 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}`;
}
}
const student = new Student('Bob', 18, 12);
console.log(student.study()); // 输出: Bob is studying in grade 12
静态方法与属性
通过 static 关键字定义静态方法或属性,直接通过类访问而非实例。
class MathUtils {
static PI = 3.14159;
static square(x) {
return x * x;
}
}
console.log(MathUtils.square(4)); // 输出: 16
console.log(MathUtils.PI); // 输出: 3.14159
Getter 与 Setter
使用 get 和 set 定义属性的访问器,控制属性的读写逻辑。

class Circle {
constructor(radius) {
this._radius = radius;
}
get area() {
return Math.PI * this._radius 2;
}
set radius(value) {
if (value <= 0) throw new Error('Radius must be positive');
this._radius = value;
}
}
const circle = new Circle(5);
console.log(circle.area); // 输出: 78.53981633974483
circle.radius = 10; // 调用 setter
私有字段
ES2022 引入私有字段语法,通过 # 前缀定义仅类内部可访问的属性或方法。
class Counter {
#count = 0; // 私有字段
increment() {
this.#count++;
}
get value() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.value); // 输出: 1
// console.log(counter.#count); // 报错: Private field '#count' must be declared in class 'Counter'
类表达式
类可以通过表达式形式定义,适合动态生成类或匿名类场景。
const Animal = class {
constructor(name) {
this.name = name;
}
};
const dog = new Animal('Dog');
console.log(dog.name); // 输出: Dog






