类(Class):事物的「设计图纸」
假设我们要设计一款"动物养成游戏",class
就是动物的通用模板
js
class Animal {
// 1. 构造函数:初始化属性(像出生登记)
constructor(name) {
this.name = name; // this 指向创建的实例
Animal.total++; // 静态属性统计总数
}
// 2. 实例方法:动物的行为(每个实例都可调用)
eat(food) {
console.log(`${this.name} 吃${food}`);
}
// 3. 静态方法:属于类本身的功能(如全局统计)
static count() {
console.log(` 共有${Animal.total} 只动物`);
}
}
Animal.total = 0; // 静态属性(需在类外声明)
// 创建实例(按图纸造动物)
const dog = new Animal("旺财");
dog.eat(" 骨头"); // "旺财吃骨头"
Animal.count(); // "共有1只动物"
关键点:
constructor
:new
时自动触发,用于初始化属性- 实例方法:通过对象调用(如
dog.eat()
) - 静态方法:通过类名调用(如
Animal.count()
),处理与类相关的全局逻辑
继承(Extends):子类复用父类能力
如果需要新增"猫类",继承 Animal
的基础能力并扩展新功能
js
class Cat extends Animal {
constructor(name, color) {
super(name); // 关键!调用父类构造函数(必须第一行)
this.color = color;
}
// 新增子类方法
climbTree() {
console.log(`${this.name} 爬树`);
}
// 重写父类方法(可选)
eat(food) {
super.eat(food); // 先调用父类方法
console.log(" 优雅舔爪~"); // 扩展新行为
}
}
// 创建子类实例
const cat = new Cat("小白", "白色");
cat.eat(" 鱼"); // "小白吃鱼 → 优雅舔爪~"
cat.climbTree(); // "小白爬树"
console.log(cat instanceof Animal); // true
关键点:
extends
:声明继承关系(Cat
自动获得Animal
的方法)super(name)
:调用父类构造函数(必须在子类构造开头使用)- 方法覆盖:子类可重写或扩展父类方法
super
关键字的三种使用情况
场景 | 作用 | 示例 |
---|---|---|
构造函数中 | 调用父类构造函数 | super(参数) |
普通方法中 | 调用父类方法(避免覆盖丢失) | super.父类方法() |
静态方法中 | 调用父类的静态方法 | super.静态方法() |
js
class Bird extends Animal {
fly() {
super.eat(" 虫子"); // 调用父类方法
console.log(" 飞翔中...");
}
}
类与继承 vs ES5 传统写法的区别
特性 | ES6 类 | ES5 原型链 |
---|---|---|
代码结构 | 清晰(class extends 语义明确) |
繁琐(手动操作 prototype ) |
继承逻辑 | 先创建父类实例,再用子类修饰 | 先创建子类实例,再绑定父类方法 |
静态方法 | 原生支持(static 关键字) |
需直接挂载到构造函数 |
私有属性(新) | 支持 #字段名 (如 #age ) |
无原生方案 |
牢记
"类是模板,继承是复用------extends
复制蓝图,super
打通父子车间"