JavaScript中的类是ES6语法糖,基于原型机制提供更清晰的面向对象编程方式。使用class定义类,包含constructor初始化实例,方法无需function关键字且挂载于原型;static定义静态方法,属类本身;通过extends实现继承,子类需调用super()并可重写父类方法;ES2022支持#前缀的私有字段和公共字段语法,提升封装性与可读性。

JavaScript 中的类(Class)是 ES6 引入的一种语法糖,让开发者可以用更接近传统面向对象语言的方式来创建对象和实现继承。虽然底层依然是基于原型(prototype)的机制,但 class 的写法更清晰、更易理解。
使用 class 关键字可以定义一个类。类中通常包含一个 constructor 方法用于初始化实例,以及其它自定义方法。
示例:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`你好,我是${this.name},今年${this.age}岁`);
}
}
const p1 = new Person("小明", 25);
p1.sayHello(); // 输出:你好,我是小明,今年25岁
说明:
立即学习“Java免费学习笔记(深入)”;
使用 static 关键字定义的方法属于类本身,而不是实例。不能通过实例调用,只能通过类名调用。
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(2, 3)); // 输出:5
// const mu = new MathUtils();
// mu.add(2, 3); // 报错:mu.add is not a function
静态方法常用于工具类或与类相关但不依赖实例数据的操作。
使用 extends 可以实现类的继承,子类可以继承父类的属性和方法。在子类的 constructor 中必须先调用 super(),否则无法使用 this。
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数
this.grade = grade;
}
study() {
console.log(`${this.name} 正在学习,年级:${this.grade}`);
}
// 重写父类方法
sayHello() {
console.log(`我是学生 ${this.name},${this.age}岁,读${this.grade}年级`);
}
}
const s1 = new Student("小红", 20, "大三");
s1.sayHello(); // 输出:我是学生 小红,20岁,读大三
s1.study(); // 输出:小红 正在学习,年级:大三
关键点:
现代 JavaScript 支持在类中定义私有字段,使用 # 前缀表示,外部无法访问。
class BankAccount {
#balance = 0; // 私有字段
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// console.log(account.#balance); // 语法错误:无法外部访问
公共字段语法允许直接在类中定义属性,无需放在 constructor 中:
class Counter {
count = 0; // 公共字段
increment() {
this.count++;
}
}
</font>
这种写法更简洁,适合初始化默认值。
基本上就这些。class 让 JavaScript 的面向对象编程更直观,结合 extends、super、static 和私有字段,已经能满足大多数场景的需求。虽然本质仍是原型继承,但语法更现代、更易维护。
以上就是JavaScript中的类(Class)与继承详解_js ES6+的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号