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

Now then, Object.create() will take an optional second parameter when it eventually arrives,<br />

which is an object containing members to add to the clone. So, let’s define a second function named<br />

emulate() that does the same thing while we wait for better days:<br />

var emulate = function (donor, more) {<br />

var Proxy = function () {}, child, m;<br />

Proxy.prototype = donor;<br />

child = new Proxy();<br />

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

child[m] = more[m];<br />

}<br />

return child;<br />

};<br />

Now say we’ve made a quart of chocolate ice cream and want to make a quart of Ben & Jerry’s New<br />

York Super Fudge Chunk. We can do so by passing the chocolate quart plus the additional ingredients to<br />

emulate(). Try it, verifying your work with Figure 5–18:<br />

var emulate = function (donor, more) {<br />

var Proxy = function () {}, child, m;<br />

Proxy.prototype = donor;<br />

child = new Proxy();<br />

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

child[m] = more[m];<br />

}<br />

return child;<br />

};<br />

var chocolate = {<br />

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

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

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

yolks: [6],<br />

cocoa: [3/8, "cup", "Callebaut, Dutch process"],<br />

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

};<br />

var newYorkSuperFudgeChunk = emulate(chocolate, {<br />

pecans: [1/4, "cup, coarsely chopped"],<br />

walnuts: [1/4, "cup, coarsely chopped"],<br />

almonds: [1/4, "cup, coarsely chopped"],<br />

whiteChocolate: [1/3, "cup, coarsely chopped", "Callebaut"],<br />

bittersweetChocolate: [1/3, "cup, coarsely chopped", "Callebaut"]<br />

});<br />

console.dir(chocolate);<br />

console.dir(newYorkSuperFudgeChunk);<br />

173

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

Saved successfully!

Ooh no, something went wrong!