# 1. 看似"多态"的一段代码
我们听的比较多的一种说法是:
多态的实际含义是:同一操作作用于不同的对象上,可以产生不同的解释和不同的执行结果。
用例子🌰来说话吧。
假设我家现在养了两只宠物,一只是小猫咪🐱,一只是小狗🐶。现在我对它们发号一个指令让它们叫。
小猫咪需要"喵喵喵~"的叫,而小狗则要"汪汪汪!"。
让它们叫就是同一操作,叫声不同就是不同的执行结果。
如果想要你转换为代码你会如何设计呢?
让我们来理一下,我们需要:
- 一个发出声音的方法
makeSound - 一个猫的类
Cat - 一个狗的类
Dog - 当调用
makeSound并且传入的是一只猫则打印出"喵喵喵~" - 当调用
makeSound并且传入的是一只狗则打印出"汪汪汪!"
那么我们很容易就得出以下这段代码了:
function makeSound (animal) {
if (animal instanceof Cat) {
console.log('喵喵喵~')
} else if (animal instanceof Dog) {
console.log('汪汪汪!')
}
}
class Cat {}
class Dog {}
makeSound(new Cat()) // '喵喵喵~'
makeSound(new Dog()) // '汪汪汪!'
@前端进阶之旅: 代码已经复制到剪贴板
当然上面👆这种做法虽然实现了我们想要的"多态性",makeSound确实是实现了传入不同类型的对象就产生不同效果的功能,但是想想如果现在我家又多养了一只小猪🐷呢?我想让它发出"啂妮妮"的叫声是不是又得去修改makeSound方法呢?
function makeSound (animal) {
if (animal instanceof Cat) {
console.log('喵喵喵~')
} else if (animal instanceof Dog) {
console.log('汪汪汪!')
} else if (animal instanceof Pig) {
console.log('啂妮妮')
}
}
class Cat {}
class Dog {}
class Pig {}
makeSound(new Cat()) // '喵喵喵~'
makeSound(new Dog()) // '汪汪汪!'
makeSound(new Pig()) // '啂妮妮'
