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 />

}<br />

return donee;<br />

};<br />

var vanillaHeathBarCrunch = {<br />

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

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

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

yolks: [6],<br />

heathBars: [4, "bars, coarsely chopped"],<br />

vanilla: [1, "bean", "Madagascar Bourbon"]<br />

};<br />

var coffeeHeathBarCrunch = cloneMembers(vanillaHeathBarCrunch);<br />

coffeeHeathBarCrunch.coffee = [1/4, "cup, coarsely ground", "Starbucks Espresso"];<br />

Note how we test whether an object is an array by checking if it has a pop() method. We’ll cover<br />

arrays and their methods later in this chapter, but for now remember that arrays have a pop() method of<br />

type function.<br />

If we rewrote cloneMembers() as a nonrecursive function, which is to say deleted<br />

cloneMembers(donor[m], donee[m]);, then we’d have to invoke cloneMembers() eight times rather than<br />

one time. So, recursion spares us from having to key in the following, which as Figure 6–4 displays still<br />

works fine.<br />

var cloneMembers = function cloneMembers (donor, donee) {<br />

donee = donee || {};<br />

for (var m in donor) {<br />

if (donor.hasOwnProperty(m)) {<br />

if (typeof donor[m] === "object" && donor[m] !== null) {<br />

donee[m] = typeof donor[m].pop === "function" ? [] : {};<br />

} else {<br />

donee[m] = donor[m];<br />

}<br />

}<br />

}<br />

return donee;<br />

};<br />

var vanillaHeathBarCrunch = {<br />

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

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

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

yolks: [6],<br />

heathBars: [4, "bars, coarsely chopped"],<br />

vanilla: [1, "bean", "Madagascar Bourbon"]<br />

};<br />

var coffeeHeathBarCrunch = cloneMembers(vanillaHeathBarCrunch);<br />

coffeeHeathBarCrunch.heavyCream = cloneMembers(vanillaHeathBarCrunch.heavyCream,<br />

coffeeHeathBarCrunch.heavyCream);<br />

coffeeHeathBarCrunch.halfHalf = cloneMembers(vanillaHeathBarCrunch.halfHalf,<br />

coffeeHeathBarCrunch.halfHalf);<br />

coffeeHeathBarCrunch.sugar = cloneMembers(vanillaHeathBarCrunch.sugar,<br />

coffeeHeathBarCrunch.sugar);<br />

coffeeHeathBarCrunch.yolks = cloneMembers(vanillaHeathBarCrunch.yolks,<br />

coffeeHeathBarCrunch.yolks);<br />

coffeeHeathBarCrunch.heathBars = cloneMembers(vanillaHeathBarCrunch.heathBars,<br />

199

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

Saved successfully!

Ooh no, something went wrong!