js class实现
Class 的基本语法
在 JavaScript 中,class 是 ES6 引入的语法糖,用于更简洁地实现面向对象编程。class 本质上是基于原型继承的语法包装。
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person('Alice');
person.greet(); // 输出: Hello, Alice
构造函数
constructor 方法是类的默认构造方法,在 new 实例时自动调用。一个类只能有一个 constructor,如果没有显式定义,会默认添加一个空的 constructor。
class Animal {
constructor(type) {
this.type = type;
}
}
const dog = new Animal('dog');
console.log(dog.type); // 输出: dog
方法定义
类的方法直接定义在类体中,不需要 function 关键字。方法之间也不需要逗号分隔。
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
const calc = new Calculator();
console.log(calc.add(5, 3)); // 输出: 8
静态方法
使用 static 关键字定义静态方法,静态方法只能通过类名调用,不能通过实例调用。

class MathUtils {
static square(x) {
return x * x;
}
}
console.log(MathUtils.square(4)); // 输出: 16
继承
使用 extends 关键字实现继承,子类可以通过 super 调用父类的构造函数或方法。
class Vehicle {
constructor(wheels) {
this.wheels = wheels;
}
describe() {
console.log(`This vehicle has ${this.wheels} wheels`);
}
}
class Car extends Vehicle {
constructor() {
super(4); // 调用父类构造函数
}
honk() {
console.log('Beep beep!');
}
}
const myCar = new Car();
myCar.describe(); // 输出: This vehicle has 4 wheels
myCar.honk(); // 输出: Beep beep!
Getter 和 Setter
可以使用 get 和 set 关键字定义属性的存取器。

class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
}
const temp = new Temperature(25);
console.log(temp.fahrenheit); // 输出: 77
temp.fahrenheit = 86;
console.log(temp.celsius); // 输出: 30
私有字段
ES2022 引入了私有字段,通过在字段名前加 # 来定义私有属性,只能在类内部访问。
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 Person = class {
constructor(name) {
this.name = name;
}
};
const person = new Person('Bob');
console.log(person.name); // 输出: Bob
Mixin 模式
通过函数和 Object.assign 可以实现 Mixin 模式,用于多重继承。
const Flyable = {
fly() {
console.log('Flying...');
}
};
class Bird {
// ...
}
Object.assign(Bird.prototype, Flyable);
const bird = new Bird();
bird.fly(); // 输出: Flying...






