Function.prototype.extends = function (Parent) { var F = function () {}; F.prototype = Parent.prototype; this.prototype = new F(); this.prototype.constructor = this; this.superclass = Parent.prototype; return Parent; } function extend(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; } function Animal(title) { var tree = [], level = 0; this.kingdom = this.family = arguments.callee.name; this.species = this.constructor.name; this.voice = ''; this.title = title; this.greet = function (){ return this.kingdom + ' ' + this.title + ' is an ' + this.species.toLowerCase() + (this.voice? ' and it`s says ' + this.voice + '!':''); }; this.outLegs = function () { var msg = ''; if(this.legs){ msg = this.family + 's have ' + this.legs + ' legs'; } else if(this.family) { msg = this.family + 's do not have a legs'; } return msg; }; this.getTree = function(){ return tree; }; this.getLevel = function(){ return level + ') ' + this.species; }; // Closure this.init = (function(){ this.init && this.init(); return function(){ tree.push(this.family); level++; } }()); this.init(); } extend(Cat,Animal); function Cat() { this.family = arguments.callee.name; this.voice = 'mieu'; this.legs = 4; Cat.superclass.constructor.apply(this,arguments); this.init(); } Snake.extends(Animal); function Snake() { this.family = arguments.callee.name; this.voice = 'ssss'; Cat.superclass.constructor.apply(this,arguments); this.init(); // How to call / Is it possible "private" or parent class function? } Snake.prototype.init = function() { // Polymorphism ? return Animal.init.call(this) + ' ...Sh-sh-sh'; } Dog.prototype = new Animal(); // Why? function Dog(){ this.family = arguments.callee.name; this.voice = 'woof'; this.legs = 4; Animal.apply(this,arguments); this.init(); } function Beagle(){ this.family = arguments.callee.name; this.prototype = new Dog(); this.legs = 4; this.color = 'White-brown'; Dog.apply(this,arguments); this.init(); } function Boxer(){ this.family = arguments.callee.name; this.legs = 4; this.color = 'Tiger'; // Without prototype! Dog.apply(this,arguments); this.init(); } var pets = { 'Creature': Animal, 'Puh': Cat, 'Sharik': Dog, 'Kaa': Snake, 'Lex': Cat, 'Woo': Snake, 'Gog': Beagle, 'Rex': Boxer }; for(pet in pets){ var myPet = new pets[pet](pet); console.log(myPet.getLevel(), '(' + myPet.getTree().join(' > ') + ')'); console.log(myPet.greet()); console.log(myPet.outLegs()); } //console.log((new Dog()), (new Boxer())); //console.log((new Animal()), (new Cat()), (new Boxer()), (new Beagle())); //console.log(Dog.prototype, Cat.prototype, Boxer.prototype, Beagle.prototype);
div { outline: red solid 1px; width: 100px; height: 100px; }