js实现class
实现类的基本语法
在JavaScript中,使用class关键字定义类。类可以包含构造函数、方法和属性。
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关键字实现继承,子类可以覆盖或扩展父类的方法。
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 add(a, b) {
return a + b;
}
static PI = 3.14159;
}
console.log(MathUtils.add(2, 3)); // 输出: 5
console.log(MathUtils.PI); // 输出: 3.14159
Getter 与 Setter
通过get和set定义属性的访问器,用于封装逻辑。
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
set radius(value) {
if (value <= 0) throw new Error('Radius must be positive');
this._radius = value;
}
get area() {
return Math.PI * this._radius 2;
}
}
const circle = new Circle(5);
console.log(circle.area); // 输出: 78.53981633974483
circle.radius = 10;
console.log(circle.area); // 输出: 314.1592653589793
私有字段
使用#前缀定义私有字段,仅在类内部可访问。
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 must be declared in class
类表达式
类可以通过表达式形式定义,适合动态生成类。

const Animal = class {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise`;
}
};
const dog = new Animal('Dog');
console.log(dog.speak()); // 输出: Dog makes a noise
注意事项
- 类声明不会提升,必须先定义后使用。
- 类的方法默认不可枚举。
- 类中的
this指向实例,箭头函数可绑定上下文。






