Last active
February 19, 2016 04:30
-
-
Save jsstrn/a0bc21b5c57d3787611b to your computer and use it in GitHub Desktop.
JavaScript Design Patterns
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
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') |
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
// 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