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

206<br />

toString: function () { return "[object WildMaineBlueberry]";}<br />

};<br />

var wildMaineBlueberry = new WildMaineBlueberry("Dole frozen wild blueberries", "Tahitian");<br />

Array.isArray(wildMaineBlueberry.halfHalf);<br />

// true<br />

Array.isArray(wildMaineBlueberry.halfHalf[2]);<br />

// false<br />

Figure 6–9. Verifying arrayness with the native Array.isArray() method or our knock-off<br />

Rewriting cloneMembers()<br />

Now that we have a better way to verify arrayness than simply groking whether a method like pop() or<br />

slice() is defined, let’s rework cloneMembers() accordingly. Then try churning a quart of Coffee Heath<br />

Bar Crunch by cloning and augmenting a quart of Vanilla Heath Bar Crunch, verifying your work with<br />

Figure 6–10:<br />

if (Array.isArray === undefined) {<br />

Array.isArray = function(v) {<br />

return {}.toString.apply(v) === "[object Array]";<br />

};<br />

}<br />

var cloneMembers = function (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] = Array.isArray(donor[m]) ? [] : {};<br />

cloneMembers(donor[m], donee[m]);<br />

} else {

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

Saved successfully!

Ooh no, something went wrong!