js class实现
JavaScript 中的 Class 实现
JavaScript 中的 class 是 ES6 引入的语法糖,本质上是基于原型继承的封装。它提供了一种更清晰、更面向对象的方式来定义构造函数和原型方法。
基本语法
class MyClass {
constructor(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}
method1() {
return this.property1 + this.property2;
}
}
继承
使用 extends 关键字实现继承:

class ChildClass extends ParentClass {
constructor(param1, param2, param3) {
super(param1, param2); // 调用父类构造函数
this.property3 = param3;
}
method2() {
return super.method1() + this.property3; // 调用父类方法
}
}
静态方法
静态方法属于类本身而非实例:

class MathUtils {
static sum(a, b) {
return a + b;
}
}
MathUtils.sum(1, 2); // 3
Getter/Setter
可以定义属性的存取器:
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(newName) {
this._name = newName;
}
}
私有字段
ES2022 新增私有字段语法:
class Counter {
#count = 0; // 私有字段
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
注意事项
- 类声明不会被提升,必须先声明后使用
- 类中的方法默认是不可枚举的
- 类内部默认使用严格模式
- 可以省略
constructor,但实例化时会自动调用空构造函数
与传统构造函数的对比
// ES5 构造函数
function OldClass(param) {
this.prop = param;
}
OldClass.prototype.method = function() {
return this.prop;
};
// 等价于 ES6 class
class NewClass {
constructor(param) {
this.prop = param;
}
method() {
return this.prop;
}
}






