23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

226<br />

Memoization<br />

In the event that you have a function that does memory-intensive or identically repetitive work, you<br />

might want to cache its return values to a closure. Doing so is referred to as memoization. To illustrate<br />

this technique, let’s memoize our ChocolateChocolate() constructor. To do so, we’ll save a local variable<br />

named memo to a closure. Then, every time ChocolateChocolate() is invoked, we’ll add a member to memo<br />

containing the returned object. Those members will be named with a string created by gluing the<br />

parameter values together with underscores. Just for the purposes of running this in Firebug, we’ll pass<br />

the memo object to console.dir so that we can view its members following each invocation of<br />

ChocolateChocolate().<br />

So, as Figure 6–21 displays, invoking ChocolateChocolate() two times in a row with the same<br />

parameters, returns the object from memo the second time. To verify that, we can compare the return<br />

values with ===. Remember from Chapter 3 that === returns true for two objects only if their heap<br />

memory locations are the same. That is to say, to ===, no two quarts of double chocolate ice cream are<br />

the same—a quart of double chocolate ice cream can only be equal to itself.<br />

var ChocolateChocolate = function () {<br />

var memo = {};<br />

return function (bittersweet, cocoa, vanilla) {<br />

var m = bittersweet + "_" + cocoa + "_" + vanilla;<br />

if (typeof memo[m] === "object") {<br />

return memo[m];<br />

}<br />

this.bittersweet = [1, "cup", bittersweet || "Callebaut"];<br />

this.cocoa = [3, "tbs", cocoa || "Callebaut"];<br />

this.vanilla = [1, "bean", vanilla || "Madagascar Bourbon"];<br />

memo[m] = this;<br />

console.dir(memo);<br />

};<br />

}();<br />

ChocolateChocolate.prototype = {<br />

heavyCream: [1, "cup", "Organic Valley"],<br />

halfHalf: [1, "cup", "Organic Valley"],<br />

sugar: [5/8, "cup"],<br />

yolks: [6]<br />

};<br />

var chocolateChocolate = new ChocolateChocolate("Lindt");<br />

console.dir(chocolateChocolate);<br />

var chocolateChocolate2 = new ChocolateChocolate("Lindt");<br />

console.dir(chocolateChocolate);<br />

chocolateChocolate === chocolateChocolate2;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!