最近讀到一本書《JavaScript設計模式與開發實踐》上,講到js的多態,我在JavaScript高級程序編程里貌似都沒有見過關於這個的詳細講解,所以想問問大家有沒有什么推薦的文章或者博客,可以推薦給小弟的,讓小弟可以深入了解一下。
先把那本上的例子拿出來跟大家分享:
書里面的故事:本人家里養了一只雞,一只鴨。當主人向他們發出‘叫’的命令時。鴨子會嘎嘎的叫,而雞會咯咯的叫。轉化成代碼形式如下
非多態代碼示例
var makeSound = function(animal) {
if(animal instanceof Duck) {
console.log('嘎嘎嘎');
} else if (animal instanceof Chicken) {
console.log('咯咯咯');
}
}
var Duck = function(){}
var Chiken = function() {};
makeSound(new Chicken());
makeSound(new Duck());
多態的代碼示例
var makeSound = function(animal) {
animal.sound();
}
var Duck = function(){}
Duck.prototype.sound = function() {
console.log('嘎嘎嘎')
}
var Chiken = function() {};
Chiken.prototype.sound = function() {
console.log('咯咯咯')
}
makeSound(new Chicken());
makeSound(new Duck());
附(https://segmentfault.com/q/1010000003056336)(http://blog.csdn.net/xiebaochun/article/details/38749953)