javascript设计模式 - 多态

var makeSound = function(animal){
if( animal instanceof Duck){
console.log('嘎嘎嘎');
}else if(animal instanceof Chicken){
console.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(){
console.log('嘎嘎嘎');
};

var Chicken = function(){}
Chicken.prototype.sound = function(){
console.log('咯咯咯');
};

makeSound(new Duck());	//嘎嘎嘎
makeSound(new  Chicken());		//咯咯咯
相关文章
相关标签/搜索