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.

Figure 6–14. Querying local variables saved to a closure<br />

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

Another way to save default values for bittersweet chocolate, cocoa, and vanilla to a closure would<br />

be to define _bittersweet, _cocoa, and _vanilla parameters for the self-invoking function that returns<br />

the ChocolateChocolate() constructor. Then pass their values to the self-invoking function.<br />

So, as Figure 6–15 displays, saving our default values as named parameters for a closure works just<br />

as well as saving those as local variables for the closure. Note that the definition of ChocolateChocolate()<br />

is the same as in the previous sample. The reason why we did not have to change the definition of<br />

ChocolateChocolate() is that there’s no difference between named parameters and local variables on an<br />

activation object. That is to say, named parameters become local variables. The only difference between<br />

the two is the way you assign a value to them.<br />

var ChocolateChocolate = function (_bittersweet, _cocoa, _vanilla) {<br />

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

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

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

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

};<br />

}("Ghirardelli", "Callebaut", "Madagascar Bourbon");<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 />

ChocolateChocolate.toString();<br />

219

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

Saved successfully!

Ooh no, something went wrong!