前言
面向对象语言有三大特征:封装、继承和多态,那么JS作为一门面向对象语言,有多态么,又怎么实现多态呢?
定义
多态:同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。多态其实是强类型语言结的果,对于JS这种弱类型语言来说,多态是与生俱来的。比如同一个“+”在字符串之间、数值之间执行不同的运算,就是一种多态。
简单来说,不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。
案例
一个发出声音的方法makeSound,当调用makeSound传入的一只猫打印"喵喵喵~"
传入一只狗则打印出"汪汪汪~"
function makeSound(who){
who instanceof Cat ?
console.log("喵喵喵~") :
who instanceof Dog ?
console.log("汪汪汪~") :
console.log("不符合标准");
}
class Cat{};
class Dog{};
makeSound(Cat());
makeSound(Dog());
改造
多态最根本的作用就是通过把过程化的条件语句转化为对象的多态性,从而消除这些条件分支语句。
function makeSound (animal) {
if (animal.sound instanceof Function) { // 判断是否有animal.sound且该属性为函数
animal.sound()
}
}
class Cat {
sound () {
console.log('喵喵喵~')
}
}
class Dog {
sound () {
console.log('汪汪汪~')
}
}
class Pig {
sound () {
console.log('啂妮妮~')
}
}
makeSound(new Cat()) // '喵喵喵~'
makeSound(new Dog()) // '汪汪汪~'
makeSound(new Pig()) // '啂妮妮~'