Polymorphism
Polymorphism is the actual meaning: the same operation applied to different objects above, and may be different interpretations of the different execution result. In other words, when sending the same message to different objects, which give different feedback news respectively
var MakeSound = function (Animal) { IF (Animal the instanceof Duck) { the console.log ( 'Gaga Ga' ); } the else IF (Animal the instanceof Chicken) { the console.log ( 'Kaka Lo' ); } }; var Duck = function () {}; var Chicken = function () {}; MakeSound ( new new Duck ()); // Ga Gaga MakeSound ( new new Chicken ()); // Kaka Lo
Things disadvantage of the above code is added for each animal must change makesound function, modify the code risk is relatively large, and multi-state idea is unchanged and may change things separate.
var makeSound = function( animal ){ animal.sound(); };
Then the variable part of their package together, we just talked about polymorphism actually refers to the polymorphism of object:
var Duck = function () {} Duck.prototype.sound = function () { the console.log ( 'Gaga Ga' ); }; var Chicken = function () {} Chicken.prototype.sound = function () { Console. log ( 'Kaka Lo' ); }; MakeSound ( new new Duck ()); // Ga Gaga MakeSound ( new new Chicken ()); // Kaka Lo
Added at a later time in the animal back and add additional direct constructor prototype on it
The fundamental role of polymorphism is through the process of conditional branch statements into an object polymorphism, thereby
Elimination of these conditional branching statements
var googleMap = { Show: function () { the console.log ( 'start rendering Google Maps " ); } }; var baiduMap = { Show: function () { the console.log ( ' start rendering Baidu map ' ); } }; var RenderMap = function (type) { IF (type === 'Google' ) { googleMap.show (); } the else IF (type === 'baidu' ) { baiduMap.show (); } }; RenderMap ( ' Google '); // output: start rendering Google Maps RenderMap ( 'baidu'); // output: start rendering Baidu map
Modified
var RenderMap = function (Map) { IF (map.show the instanceof Function) { map.show (); } }; RenderMap (googleMap); // Output: Renders Google Maps RenderMap (baiduMap); // Output: Renders Baidu map