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 5 ■ MEMBER INHERITANCE<br />

174<br />

Figure 5–18. Adding members in prototypal inheritance<br />

Cloning Members<br />

Another way to clone an object is to do a deep copy of its members. Unlike emulate() shown earlier,<br />

which does a shallow copy of members (that is, members of the object type are copied by reference), a<br />

deep copy recursively clones those. Let’s write a helper function named cloneMembers() that will clone<br />

an object by doing a deep copy of its members, deferring the explanation of recursion until Chapter 6.<br />

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

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

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

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

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

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

} else {<br />

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

}<br />

}<br />

return donee;<br />

};<br />

Now if we want to make a quart of Ben & Jerry’s Coffee Heath Bar Crunch from Vanilla Heath Bar<br />

Crunch, we’d clone the latter by doing a deep copy of its members. Then add a coffee member, verifying<br />

our work with Figure 5–19. Note that coffeeHeathBarCrunch does not inherit members from<br />

vanillaHeathBarCrunch via the prototype chain. Rather, coffeeHeathBarCrunch has deep copies of<br />

vanillaHeathBarCrunch members. So, no prototype chain this time.

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

Saved successfully!

Ooh no, something went wrong!