用对象的多态性消除条件分支
var makeSound = function (animal) {
if (animal instanceof Duck) {
console.log('嘎嘎嘎')
} else if (animal instanceof Chicken) {
cosnole.log('咯咯咯')
}
}
var Duck = function () {}
var Chicken = function () {}
makeSound(new Duck()) // 嘎嘎嘎
makeSound(new Chicken()) // 咯咯咯
var makeSound = function (animal) {
animal.sound()
}
var Duck = function () {}
Duck.prototype.sound = function () {
cosnole.log('嘎嘎嘎')
}
var Chicken = function () {}
Chiken.prototype.sound = function () {
console.log('咯咯咯')
}
makeSound(new Duck()) // 嘎嘎嘎
makeSound(new Chiken()) // 咯咯咯
通过多态改写之后新增可以直接新增一种动物类,只要定义了sound方法就可以直接调用makeSound来让其发出声音了,而之前则是必须改动makeSound方法,写出大量的if/else逻辑,当逻辑变得十分复杂的时候就不是那么容易维护了。