多态的思想实际上是吧做什么以及谁去做分离开来。
多态最根本的作用就是通过把过程化的条件分支语句转化为对象的多态性,从而消除这些条件分支语句。
var makeSound = function(animal){
if(animal instanceof Duck){
console.log('GAGAGA');
}else if(animal instanceof Chicken){
console.log('GeGeGe');
}
}
var Duck = function(){}
var Chicken = function(){}
makeSound(new Duck());
makeSound(new Chicken());
抽离公共方法sound 提现对象的多态性
/*对象的多态性*/
var Duck = function(){}
var Chicken = function(){}
var makeSound = function (animal){
animal.sound();
}
Duck.prototype.sound = function(){
console.log('GAGAGA');
}
Chicken.prototype.sound =function(){
console.log('GeGeGe');
}
makeSound(new Duck());
makeSound(new Chicken());
var Dog =function(){}
Dog.prototype.sound = function(){
console.log('WAWAWA');
}
makeSound(new Dog());