Last active
August 29, 2015 14:08
-
-
Save TessMyers/e7d2c28ec2d881ef9d65 to your computer and use it in GitHub Desktop.
Functional instantiation with shared methods
This file contains hidden or 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
// 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