JavaScript 的类语法是 ES6 (ECMAScript 2015) 引入的,它提供了一种更清晰、更接近传统面向对象语言的方式来创建对象和处理继承。虽然 JavaScript 本质上仍然是基于原型的语言,但类语法提供了更直观的语法糖。
基本类定义
javascript
复制
下载
class Person { // 构造函数 constructor(name, age) { this.name = name; this.age = age; } // 方法 greet() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } } // 使用类 const person = new Person('Alice', 30); person.greet(); // 输出: Hello, my name is Alice and I'm 30 years old.
类的主要特性
1. 构造函数
-
使用
constructor
方法定义 -
在创建类实例时自动调用
-
用于初始化对象属性
2. 方法
-
类中定义的方法会自动添加到类的原型上
-
方法之间不需要逗号分隔
3. 静态方法
-
使用
static
关键字定义 -
只能通过类本身调用,不能通过实例调用
javascript
复制
下载
class MathUtils { static square(x) { return x * x; } } console.log(MathUtils.square(5)); // 25
4. 类的继承
-
使用
extends
关键字实现继承 -
子类可以通过
super
调用父类的构造函数和方法
javascript
复制
下载
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 student = new Student('Bob', 18, 12); student.greet(); // 继承自Person的方法 student.study(); // 输出: Bob is studying in grade 12.
5. Getter 和 Setter
-
可以定义属性的访问器
javascript
复制
下载
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.height * this.width; } set sideLength(value) { this.height = value; this.width = value; } } const rect = new Rectangle(5, 10); console.log(rect.area); // 50 (getter) rect.sideLength = 7; // setter console.log(rect.area); // 49
6. 私有字段(ES2022)
-
使用
#
前缀定义私有字段 -
只能在类内部访问
javascript
复制
下载
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
类与传统构造函数的区别
虽然类语法看起来与传统构造函数不同,但底层实现仍然是基于原型的:
javascript
复制
下载
// 传统构造函数 function Person(name) { this.name = name; } Person.prototype.greet = function() { console.log(`Hello, ${this.name}`); }; // 类语法 class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, ${this.name}`); } }
类语法的主要优势在于:
-
语法更简洁直观
-
内置继承支持
-
更清晰的静态方法定义
-
更好的代码组织和可读性
注意事项
-
类声明不会被提升(与函数声明不同)
-
类中的所有代码默认在严格模式下执行
-
类的方法不可枚举(与通过原型添加的方法不同)
-
调用类必须使用
new
关键字,否则会抛出错误
JavaScript 的类语法使得面向对象编程更加直观,特别是对于有其他面向对象语言经验的开发者来说更容易上手。