javascript 的 class 是基于原型的语法糖,本质未变但写法更简洁;支持 constructor、静态方法、私有字段(#)、继承(extends/super)、getter/setter 等特性。

JavaScript 中用 class 语法糖定义类,本质仍是基于原型(prototype)的面向对象机制,只是写法更简洁、语义更清晰。它不改变底层逻辑,但让构造函数、原型方法、继承等操作更直观。
基本 class 定义与实例化
使用 class 关键字声明类,内部用 constructor() 方法定义初始化逻辑;通过 new 创建实例。
-
constructor是唯一必需的方法,用于设置实例属性 - 类体中直接定义的方法会自动添加到类的
prototype上(不可枚举) - 类声明不会被提升(hoisting),必须先定义后使用
示例:
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
return `Hello, I'm ${this.name}`;
}
}
const p = new Person('Alice', 30);
console.log(p.sayHello()); // "Hello, I'm Alice"
静态方法与实例属性(含公有/私有)
用 static 关键字定义静态方法,只能通过类名调用;ES2022 起支持公有和私有字段语法(# 开头)。
- 静态方法不绑定实例,常用于工具函数或工厂逻辑
- 公有实例字段(如
name = 'default')在构造前初始化,无需写在constructor中 - 私有字段(
#count)和私有方法(#helper())仅在类内部可访问,外部无法读写
示例:
class Counter {#count = 0;
static totalCount = 0;
constructor() {
Counter.totalCount++;
}
get value() { return this.#count; }
increment() { this.#count++; }
#log() { console.log('updated'); }
update() {
this.increment();
this.#log();
}
}
const c1 = new Counter();
c1.update(); // 输出 'updated'
// c1.#count → 报错:私有字段不可访问
继承:extends 与 super
用 extends 实现类继承,子类中必须在使用 this 前调用 super()(即父类构造函数)。
-
super()在子类constructor中调用,用于初始化this -
super.xxx可调用父类的属性、方法或静态成员 - 子类可重写父类方法,也可用
super.method()在重写中复用父逻辑
示例:
class Animal {constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound.`; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须!
this.breed = breed;
}
speak() {
return super.speak().replace('sound', 'bark') + ` It's a ${this.breed}.`;
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
console.log(dog.speak()); // "Buddy makes a bark. It's a Golden Retriever."
getter/setter 与计算属性封装
在 class 内部可用 get 和 set 定义访问器属性,实现对私有状态的安全读写控制。
-
get方法无参数,调用时像访问普通属性(如obj.fullName) -
set方法接收一个参数,赋值时触发(如obj.age = 25) - 适合做数据校验、格式转换、依赖更新等逻辑
示例:
class User {#firstName = '';
#lastName = '';
get fullName() {
return `${this.#firstName} ${this.#lastName}`.trim();
}
set firstName(value) {
if (typeof value === 'string') this.#firstName = value.trim();
}
set lastName(value) {
if (typeof value === 'string') this.#lastName = value.trim();
}
}
const u = new User();
u.firstName = ' John ';
u.lastName = ' Doe ';
console.log(u.fullName); // "John Doe"
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











