js class实现
JavaScript 类实现
在 JavaScript 中,可以使用 class 关键字来实现面向对象的编程。类是一种模板,用于创建对象,可以包含构造函数、方法和属性。
基本类定义
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
创建实例
const person1 = new Person('Alice', 30);
person1.greet(); // 输出: Hello, my name is Alice and I am 30 years old.
继承
类可以通过 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 student1 = new Student('Bob', 20, 'A');
student1.greet(); // 输出: Hello, my name is Bob and I am 20 years old.
student1.study(); // 输出: Bob is studying in grade A.
静态方法
静态方法属于类本身,而不是类的实例。可以通过类名直接调用。

class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(5, 3)); // 输出: 8
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;
}
}
}
使用 Getter 和 Setter
const rect = new Rectangle(10, 20);
console.log(rect.area); // 输出: 200
rect.width = 15;
console.log(rect.area); // 输出: 300
私有字段
ES2022 引入了私有字段,通过在字段名前加 # 来定义私有属性。
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
使用私有字段
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
JavaScript 的类提供了一种清晰和结构化的方式来组织和复用代码,适合构建复杂的应用程序。






