Skip to content

Instantly share code, notes, and snippets.

@TessMyers
Last active August 29, 2015 14:08
Show Gist options
  • Save TessMyers/e7d2c28ec2d881ef9d65 to your computer and use it in GitHub Desktop.
Save TessMyers/e7d2c28ec2d881ef9d65 to your computer and use it in GitHub Desktop.
Functional instantiation with shared methods
// Makes two animals that have their own animal sound methods, but share a common .eat method
var makeCat = function(){
var cat = {};
cat.stomach = [];
cat.meow = function(){
console.log("MEOW");
};
_.extend(cat, animalMethods);
return cat;
};
var makeDog = function (){
var dog = {};
dog.stomach = [];
dog.bark = function(){
console.log("WOOFWOOF");
};
_.extend(dog, animalMethods)
return dog;
};
var animalMethods = {
eat: function(food){
this.stomach.push(food);
}
};
var kitty = makeCat();
var pupDog = makeDog();
kitty.meow(); // "MEOW"
pupDog.bark(); // "WOOFWOOF"
kitty.eat('owner');
console.log(kitty.stomach); // ["owner"]
pupDog.eat('kitty');
console.log(pupDog.stomach); // ["kitty"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment