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()); //咯咯咯