Menu
CoddyTech

什么是多态?

本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 35 课,共 56 课。

多态是面向对象编程的核心原则,它允许不同类的对象以不同方式响应同一个方法。

在 JavaScript 中,多态最常见的情况是子类重写父类的方法。

我们来创建一个简单的父类,并添加一个 speak() 方法:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
}

现在,我们来创建一个继承 Animal 的子类:

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

这是另一个子类:

class Cat extends Animal {
  speak() {
    return `${this.name} meows`;
  }
}

每个子类实现 speak() 方法的方式都不同。这就是多态的实际应用!

现在,我们可以创建不同的对象,并对每个对象调用同一个方法:

const animal = new Animal("Some animal");
const dog = new Dog("Rex");
const cat = new Cat("Whiskers");

console.log(animal.speak()); // Some animal 发出了声音
console.log(dog.speak());    // Rex 汪汪叫
console.log(cat.speak());    // Whiskers 喵喵叫

这三个对象都会响应 speak() 方法,但每个对象的响应方式都不同。

challenge icon

挑战

你有一个通知系统,其中包含一个父类 Notification 和两个子类。你的任务是在每个子类中添加 send(message) 方法,并为它们实现不同的功能。

  1. 在 EmailNotification 类中,该方法应返回字符串:"Sending '(message)' via Email"
  2. 在 SMSNotification 类中,该方法应返回字符串:"Sending '(message)' via SMS"

亲手试试

import { EmailNotification } from './email-notification.js';
import { SMSNotification } from './sms-notification.js';

// 测试代码,不要修改
const email = new EmailNotification();
const sms = new SMSNotification();

console.log(email.send("Hello!"));  // 应使用 EmailNotification 的 send()
console.log(sms.send("Hello!"));    // 应使用 SMSNotification 的 send()
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: JavaScript 在线编译器