JavaScript中class是ES6引入的语法糖,本质基于原型继承;需含constructor,实例方法直接定义在类体内,支持static、getter/setter及extends继承。

在 JavaScript 中,用 class 关键字定义类是 ES6 引入的语法糖,本质仍是基于原型的继承,但写法更清晰、更接近传统面向对象语言。
基础语法:定义空类和构造函数
使用 class 声明一个类,必须包含 constructor 方法(否则会自动生成空构造器);它会在实例化时自动调用。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
创建实例:const p = new Person('Alice', 30);
添加实例方法(不需 function 关键字)
方法直接写在类体内,**不能**加 function 关键字,也不能加逗号分隔。
- 方法默认添加到类的原型上(
Person.prototype.sayHello) - 不支持可计算属性名或简写生成器(如
*method(){}),但普通 generator 可以写成*[Symbol.iterator]() {}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
haveBirthday() {
this.age++;
}
}
定义静态方法和 getter/setter
static 开头的方法属于类本身,不被实例继承;get/set 用于定义属性访问器。
class Person {
constructor(name, age) {
this._name = name;
this.age = age;
}
get name() {
return this._name;
}
set name(value) {
if (typeof value === 'string' && value.trim()) {
this._name = value.trim();
}
}
static createAnonymous() {
return new Person('Anonymous', 0);
}
}
const p = new Person('Bob', 25);
console.log(p.name); // "Bob"
Person.createAnonymous(); // 实例化一个匿名对象
继承:用 extends 和 super
子类通过 extends 继承父类;子类构造器中必须先调用 super()(否则无法访问 this)。
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}`);
}
}
子类可重写父类方法,也可用 super.methodName() 调用父类版本。


















