🧱 1. 类(Class)
类就是一种 模板或蓝图,用来描述一类对象的属性和行为(方法),通过它可以创建多个类似的对象。
✅ JS示例:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} 发出声音`);
}
}
const dog = new Animal('狗');
dog.speak(); // 狗 发出声音
👉 这里 Animal 是类,dog 是通过类实例化出来的对象。
📦 2. 封装(Encapsulation)
封装是指把属性和方法封装在对象内部,不对外暴露实现细节,只暴露必要的接口,避免外部随意修改对象。
✅ JS示例:
class Person {
#age; // 私有属性
constructor(name, age) {
this.name = name;
this.#age = age;
}
getAge() {
return this.#age;
}
}
const p = new Person('小明', 25);
console.log(p.getAge()); // 25
console.log(p.#age); // ❌ 报错,私有属性外部无法访问
🧬 3. 继承(Inheritance)
子类通过继承可以复用父类的属性和方法,并且可以扩展或重写。
✅ JS示例:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} 在叫`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} 汪汪叫`);
}
}
const d = new Dog('小狗');
d.speak(); // 小狗 汪汪叫
👉 Dog 继承了 Animal,并重写了 speak 方法。
🧩 4. 多态(Polymorphism)
多态指同一方法在不同对象上的表现不同。在JS里通过继承+方法重写体现。
✅ JS示例:
class Animal {
speak() {
console.log('动物叫');
}
}
class Cat extends Animal {
speak() {
console.log('猫 喵喵叫');
}
}
class Dog extends Animal {
speak() {
console.log('狗 汪汪叫');
}
}
const animals = [new Cat(), new Dog(), new Animal()];
animals.forEach(animal => animal.speak());
📌 输出:
猫 喵喵叫
狗 汪汪叫
动物叫
👉 调用同样的 speak,不同子类的表现不同。
✅ 总结
| 概念 | 作用 | JS关键点 |
|---|---|---|
| 类 | 定义对象模板 | class |
| 封装 | 隐藏实现细节 | # 私有属性、get/set |
| 继承 | 复用父类 | extends、super |
| 多态 | 不同子类同方法不同表现 | 方法重写 |