Skip to content

Instantly share code, notes, and snippets.

@TessMyers
Created October 31, 2014 05:47
Show Gist options
  • Save TessMyers/ddb7fa580cbb4034b6e0 to your computer and use it in GitHub Desktop.
Save TessMyers/ddb7fa580cbb4034b6e0 to your computer and use it in GitHub Desktop.
Prototypal instantiation
// Creates a basic cat with meow and eat methods, then creates a kitten object that inherits from
// Makes cats with meow and eat methods, plus a stomach (just for hairballs)
var makeCat = function(name){
var cat = Object.create(catMethods);
cat.stomach = [];
return cat;
};
var catMethods = {
meow: function(){
console.log("MEOW");
},
eat: function(food){
this.stomach.push(food);
}
};
// make a kitten that does everything a cat does, but can also play with yarn.
var makeKitten = function(){
// Macig! The kitten inherits all methods from the parent cat
var kitten = Object.create(cat);
kitten.play = function(){
console.log('*chases ball of yarn*');
};
return kitten;
}
// Make a cat! meowpurr
var cat = makeCat();
// make a kitten!
var kitty = makeKitten();
// kitty can eat, meow, and play
kitty.eat('fingers')
console.log(kitty.stomach) // ["fingers"]
kitty.play() // *chases ball of yarn*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment