您的位置:首页 > Web前端 > JavaScript

javascript设计模式 - 多态

2016-07-31 00:00 351 查看
摘要: 多态背后的思想是将“做什么" 和”谁去做以及怎么做“ 分离开来。也就是将”不变的事物“ 和 ”可能改变的事物“ 分离开来。

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());		//咯咯咯
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 多态