Skip to content

Instantly share code, notes, and snippets.

@ovaillancourt
Created April 5, 2012 18:41
Show Gist options
  • Save ovaillancourt/2313159 to your computer and use it in GitHub Desktop.
Save ovaillancourt/2313159 to your computer and use it in GitHub Desktop.
Prototype chains + constructor-based initialization using Object.create
//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