/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php ?> <html> <head> <style> </style> </head> <body> <script> //Contain all in anonymous self executing func to create namespace //Create object instances and assign to window global object //Always execute copyPrototype() right after class constructor and before defining prototype functions. //Ref: http://blogs.sitepoint.com/javascript-inheritance/ (function (win) { var my = {}; function rtrim(val) { return val.replace(/\s+$/,""); } //private method function copyPrototype(descendant, parent) { var sConstructor = parent.toString(); var aMatch = sConstructor.match( /\s*function (.*)\(/ ); //fix ie 6 problem if their is trailing space after func name then trim it aMatch[1] = rtrim(aMatch[1]); if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } for (var m in parent.prototype) { descendant.prototype[m] = parent.prototype[m]; } //console.log(descendant.prototype); }; function Animal () { this.species = "animal"; } Animal.prototype.category = function() { alert(this.species); }; Animal.prototype.contest = function() { alert('Animal contest'); }; function Dog() { //Calling parent constructor this.Animal(); this.species += ":dog"; } // Dog "inherits" from Animal copyPrototype(Dog, Animal); function Poodle() { this.Dog(); this.species += ":poodle"; } // Poodle "inherits" from Dog copyPrototype(Poodle, Dog); Poodle.prototype.contest = function() { alert('Poodle contest'); }; //public instances my.Dog = new Dog(); my.Poodle = new Poodle(); //Create closure. assign to window object to make available to global space win.$Noah = my; }(window)); //****** Single inheritance. //displays animal:dog. $Noah.Dog.category(); //****** multiple inheritance //displays animal:dog:poodle $Noah.Poodle.category(); //****** Child with multiple parents //Dog inherits from both Animal and Quadruped classes //copyPrototype(Dog, Animal); //copyPrototype(Dog, Quadruped); //****** method overriding //Executes super class contest() //Displays 'Animal Contest' $Noah.Dog.contest(); //Executes overriden contest() in Poodle class //Displays 'Poodle Contest' $Noah.Poodle.contest(); </script> </body> </html>