JavaScript 的 class 是构造函数与原型链的语法糖,不引入新机制;它统一初始化逻辑于 constructor,自动将方法挂载到原型,简化继承(extends + super),但底层仍基于原型。

JavaScript 中用 class 语法不是引入新机制,而是对构造函数 + 原型链的语法糖封装,让定义更清晰、写法更简洁。
定义构造函数和实例属性更直观
传统方式需手动在构造函数中用 this 赋值;class 把初始化逻辑统一收在 constructor 方法里,语义明确:
✅ 推荐写法:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
❌ 对比传统写法(易遗漏 new 或写错 this):
function Person(name, age) {
this.name = name;
this.age = age;
}
方法自动挂载到原型上,不用再手动赋值
类中定义的普通方法(非 static)会自动添加到 Person.prototype,无需像以前那样写 Person.prototype.sayHello = function() {...}:
将后端 Java 接口文档转换为前端 TypeScript 类型定义(interface / type)。输入:飞书文档、Spring Boot 接口文档、Swagger/OpenAPI、手写 API 文档等。输出:包含请求参数与响应结果的 .md 文件,含完整 JSDoc 注释。触发关键词:Java 转 TS、接口转换、生成前端类型、接口文档转 TypeScript、DTO/VO/BO 转 interface、后端文档转前端类型、生成接口类型、类型定义生成。
class Person {
constructor(name) {
this.name = name;
}
sayHello() { // 自动成为原型方法
console.log(`Hello, I'm ${this.name}`);
}
static createAdult(name) { // 静态方法,挂在类本身
return new Person(name, 18);
}
}
这样既避免手写原型链的出错风险,也更符合面向对象直觉。
继承写法大幅简化,extends + super() 替代 Object.setPrototypeOf 和手动调用父构造
子类继承父类时,extends 自动设置原型链,super() 确保父类构造函数正确执行:
- 子类必须在
constructor中第一行调用super()(否则报错) -
super不仅可调用父构造,还能访问父类原型上的方法(如super.sayHello()) - 不再需要手动写
Student.prototype = Object.create(Person.prototype)这类易错代码
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // ✅ 必须先调用
this.grade = grade;
}
study() {
console.log(`${this.name} is studying`);
}
}
注意:class 仍是基于原型,不是“真”的类系统
class 没有改变 JavaScript 的原型本质。它只是让开发者更少接触 prototype、__proto__ 等底层细节:
-
Student.prototype.__proto__ === Person.prototype依然成立 - 类声明不会被提升(和函数声明不同),必须先定义再使用
- 类内部所有方法默认是不可枚举的(符合传统原型方法行为)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










