Once I read in John Resig’s book that a constructor is like a cookie cutter to make cookies. I found that very nice of him that he thought of people like me… who… who likes cookies and try to learn JS. Well, so I made up this little example. I have a cookie cutter, cookies and someone who eats them, the Cookie Monster. 🙂
For those who don’t know Cookie Monster, this is him. Very scary guy.
This is my cookie cutter, properly said a constructor. It allows me to bake as many cookies as I want.
function MyCookie(flavor) { this.flavor = flavor; this.eaten = false; }
I am going to bake four of my favorite cookies. Each cookie has automatically property “flavor” and “eaten” which says, obviously, if the cookie was eaten or not in Booleanese language.
var cookie1 = new MyCookie('With macadamia nuts and white chocolate'); var cookie2 = new MyCookie('Chocolate chip'); var cookie3 = new MyCookie('Oatmeal raisin'); var cookie4 = new MyCookie('Peanut butter');
The Cookie Monster is one big static object. It holds a property of how many cookies he already ate and a method isHungry so he can say he is hungry and one so he can actually eat the cookies… otherwise he would be one big Hungry Cookie Monster. 🙂
var cookieMonster = new Object(); cookieMonster.numberOfEatenCookies = 0; cookieMonster.isHungry = function() { alert('Me want cookie!'); } cookieMonster.eatCookie = function(c) { if(!c.beAwareOfCookieMonster ) { //if the cookie doesn't have this method CM will eat it c.eaten = true; //rewrites cookie's property this.numberOfEatenCookies++; alert(c.flavor + ', Om nom nom nom...'); } else { //if the cookie has this method to scare CM away it is safe c.beAwareOfCookieMonster(); } }
Cookie Monster wakes up wicked hungry looking for a cookie.
// here he comes cookieMonster.isHungry(); /* and he eats 2 of my cookies, buuuu cause they can't scare the CM away */ cookieMonster.eatCookie(cookie1); cookieMonster.eatCookie(cookie2); // Both properties logs true. clearly he ate them, so sad. console.log('Cookie1 eaten: ' + cookie1.eaten); console.log('Cookie2 eaten: ' + cookie2.eaten);
I am going to protect my last cookies though and via the prototype property I will add a new method “beAwareOfCookieMonster” to all MyCookie objects.
MyCookie.prototype.beAwareOfCookieMonster = function() { alert('Hahaa, you big Cookie Monster, you cannot eat me!'); };
Cookie Monster is about to eat my last two cookies.
cookieMonster.eatCookie(cookie3); cookieMonster.eatCookie(cookie4);
But they are safe because they have the method “beAwareOfCookieMonster” Phewww. 🙂
Fight Cookie Monster on your own or listen to his famous song “C is for Cookie” song which is quite incredible 😉
One thought on “Javascript 5 – cookies vs. Cookie Monster”
Comments are closed.