Created
April 5, 2012 18:41
-
-
Save ovaillancourt/2313159 to your computer and use it in GitHub Desktop.
Prototype chains + constructor-based initialization using Object.create
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Animal constructor | |
function Animal( legCount ){ | |
this.legCount = legCount; | |
} | |
//Methods | |
Animal.prototype.legCount = function(){ | |
return( this.legCount ); | |
}; | |
//////////////////////////////////////////////////////////////////////////////// | |
//bird constructor | |
function Bird(){ | |
// Call the super constructor. | |
Person.call( this, 2); | |
// Create the traits property. | |
this.traits = {}; | |
} | |
//Extend the animal prototype using object.create. | |
Bird.prototype = Object.create( Animal.prototype ); | |
//Another method here. | |
Bird.prototype.chant = function(){ | |
return 'blablabla'; | |
} | |
// Create a bird instance | |
var parrot = new Bird(); | |
parrot.traits.color = 'rainbow'; | |
parrot.traits.diet = 'fruits'; | |
// Create another bird instance | |
var hawk = new Bird(); | |
hawk.traits.color = 'gray'; | |
hawk.traits.diet = 'meat'; | |
//////////////////////////////////////////////////////////////////////////////// | |
function Mammal(){ | |
Animal.call(this, 4); | |
} | |
Mammal.prototype = Object.create(Animal.prototype) | |
//etc.. | |
//////////////////////////////////////////////////////////////////////////////// | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment