用对象的多态性消除条件分支

    1. var makeSound = function (animal) {
    2. if (animal instanceof Duck) {
    3. console.log('嘎嘎嘎')
    4. } else if (animal instanceof Chicken) {
    5. cosnole.log('咯咯咯')
    6. }
    7. }
    8. var Duck = function () {}
    9. var Chicken = function () {}
    10. makeSound(new Duck()) // 嘎嘎嘎
    11. makeSound(new Chicken()) // 咯咯咯
    1. var makeSound = function (animal) {
    2. animal.sound()
    3. }
    4. var Duck = function () {}
    5. Duck.prototype.sound = function () {
    6. cosnole.log('嘎嘎嘎')
    7. }
    8. var Chicken = function () {}
    9. Chiken.prototype.sound = function () {
    10. console.log('咯咯咯')
    11. }
    12. makeSound(new Duck()) // 嘎嘎嘎
    13. makeSound(new Chiken()) // 咯咯咯

    通过多态改写之后新增可以直接新增一种动物类,只要定义了sound方法就可以直接调用makeSound来让其发出声音了,而之前则是必须改动makeSound方法,写出大量的if/else逻辑,当逻辑变得十分复杂的时候就不是那么容易维护了。