Skip to content

Instantly share code, notes, and snippets.

@jsstrn
Last active February 19, 2016 04:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsstrn/a0bc21b5c57d3787611b to your computer and use it in GitHub Desktop.
Save jsstrn/a0bc21b5c57d3787611b to your computer and use it in GitHub Desktop.
JavaScript Design Patterns
function Ape (name, species, approvedListOfFoods) {
this.name = name
this.species = species
this.approvedListOfFoods = approvedListOfFoods
this.introduce = function () {
console.log('Hello! My name is ' + this.name + '. I am a ' + this.species + '. I like ' + this.approvedListOfFoods)
}
this.eat = function (food) {
if (this.approvedListOfFoods.indexOf(food) > -1) console.log('Om nom nom nom! Eating a ' + food)
else console.log('Yuck! I don\'t like ' + food)
}
}
// instantiate three apes
var m1 = new Ape('Abel', 'gorilla', ['coconut', 'apple', 'mango'])
var m2 = new Ape('Ben', 'chimp', ['banana', 'cherry', 'grapes'])
var m3 = new Ape('Chris', 'baboon', ['guava', 'strawberry', 'pineapple'])
m1.introduce()
m2.introduce()
m3.introduce()
m1.eat('grapes')
m2.eat('banana')
m3.eat('durian')
// constructor pattern
function Ape (name, species, approvedListOfFoods) {
this.name = name
this.species = species
this.approvedListOfFoods = approvedListOfFoods
}
Ape.prototype.introduce = function () {
console.log('Hello! My name is ' + this.name + '. I am a ' + this.species + '. I like ' + this.approvedListOfFoods)
}
Ape.prototype.eat = function (food) {
if (this.approvedListOfFoods.indexOf(food) > -1) console.log('Om nom nom nom! Eating a ' + food)
else console.log('Yuck! I don\'t like ' + food)
}
// instantiate three apes
var m1 = new Ape('Abel', 'gorilla', ['coconut', 'apple', 'mango'])
var m2 = new Ape('Ben', 'chimp', ['banana', 'cherry', 'grapes'])
var m3 = new Ape('Chris', 'baboon', ['guava', 'strawberry', 'pineapple'])
m1.introduce()
m2.introduce()
m3.introduce()
m1.eat('grapes')
m2.eat('banana')
m3.eat('durian')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment