ES2015 的 class
是 JavaScript 对面向对象编程(OOP)的语法糖,它简化了基于原型链的继承和对象构造的写法,使代码更易读、更接近传统面向对象语言(如 Java/C++)的风格。以下是 ES2015 class
的核心用法和特性:
一、基本语法
1. 类声明
使用 class
关键字定义类,必须通过 new
调用构造函数:
javascript
class Person {
// 构造函数(必须命名为 constructor)
constructor(name, age) {
this.name = name; // 实例属性
this.age = age;
}
// 实例方法(定义在原型链上)
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
}
// 创建实例
const alice = new Person("Alice", 25);
alice.sayHello(); // "Hello, I'm Alice"
二、核心特性
1. 实例属性与方法
- 实例属性 :在
constructor
中通过this.xxx
定义。 - 实例方法:直接在类中定义方法,自动添加到原型链,供所有实例共享。
2. 静态属性与方法
- 静态属性/方法 :属于类本身,而非实例,通过
static
定义。
javascript
class MathUtils {
// 静态属性(ES2022+)
static PI = 3.14159;
// 静态方法
static sum(a, b) {
return a + b;
}
}
console.log(MathUtils.PI); // 3.14159
console.log(MathUtils.sum(2, 3)); // 5
3. Getter 和 Setter
用于拦截属性的读取和赋值操作:
javascript
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
// Getter(计算属性)
get area() {
return this._width * this._height;
}
// Setter
set width(value) {
if (value > 0) this._width = value;
}
}
const rect = new Rectangle(10, 20);
console.log(rect.area); // 200(通过 getter 访问)
rect.width = 30; // 通过 setter 修改
三、继承(Inheritance)
通过 extends
实现继承,super
调用父类方法:
1. 基本继承
javascript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造函数
this.breed = breed;
}
// 重写父类方法
speak() {
super.speak(); // 调用父类方法
console.log("Woof!");
}
}
const dog = new Dog("Buddy", "Golden");
dog.speak();
// 输出:
// Buddy makes a noise.
// Woof!
2. 静态方法继承
子类可以继承父类的静态方法:
javascript
class Parent {
static staticMethod() {
return "Parent Static";
}
}
class Child extends Parent {}
console.log(Child.staticMethod()); // "Parent Static"
四、私有字段和方法(ES2022+)
通过 #
前缀定义私有成员(需支持 ES2022+ 的环境):
javascript
class Counter {
#count = 0; // 私有字段
// 私有方法
#increment() {
this.#count++;
}
tick() {
this.#increment();
return this.#count;
}
}
const counter = new Counter();
console.log(counter.tick()); // 1
console.log(counter.#count); // 报错:私有字段不可访问
五、类表达式
类可以作为表达式定义(类似函数表达式):
javascript
const Person = class {
constructor(name) {
this.name = name;
}
};
const bob = new Person("Bob");
六、注意事项
-
类声明不会提升:必须先定义类,再实例化。
javascriptnew MyClass(); // 报错:MyClass 未定义 class MyClass {}
-
方法不可枚举:类中定义的方法默认不可枚举(与 ES5 不同)。
-
严格模式:类声明和类方法默认在严格模式下执行。
-
原型链本质 :
class
本质仍是基于原型链的语法糖,可通过typeof class
验证:javascriptclass Foo {} console.log(typeof Foo); // "function"
七、实际应用场景
- 封装复杂逻辑:将数据和操作封装在类中(如 UI 组件、游戏角色)。
- 代码复用:通过继承减少冗余代码。
- 静态工具类 :定义工具方法(如
MathUtils
)。
总结
ES2015 的 class
提供了一种更清晰、更接近传统 OOP 的语法,核心功能包括:
- 类声明、实例/静态属性方法、继承、Getter/Setter。
- 通过
extends
和super
实现继承。 - 使用
#
前缀定义私有成员(ES2022+)。
推荐实践 :在复杂业务逻辑中优先使用 class
,结合模块化(import/export
)组织代码,提升可维护性。