23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 6 ■ FUNCTIONS AND ARRAYS<br />

freshLemonJuice: [2, "tsp"],<br />

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

};<br />

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

wildMaineBlueberry.toString();<br />

// "[object WildMaineBlueberry]"<br />

Figure 6–6. WildMaineBlueberry.prototype.toString() overrides Object.prototype.toString().<br />

Native JavaScript constructors defined by ECMAScript or DOM always override<br />

Object.prototype.toString(). For example, if we call toString() on the array in<br />

wildMaineBlueberry.heavyCream, JavaScript glues the elements together with commas instead of<br />

returning "[object Array]", which is what Object.prototype.toString() returns for an array when it is<br />

not overridden. Similarly, if we call toString() on the constructor function WildMaineBlueberry,<br />

JavaScript return its definition as a string. Try doing both, verifying your work with Figure 6–7.<br />

var WildMaineBlueberry = function(blueberries, vanilla) {<br />

this.blueberries = [2, "cup", blueberries ? blueberries : "fresh wild Maine blueberries"];<br />

this.vanilla = [1, "bean", vanilla ? vanilla : "Madagascar Bourbon"];<br />

};<br />

WildMaineBlueberry.prototype = {<br />

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

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

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

yolks: [6],<br />

freshLemonJuice: [2, "tsp"],<br />

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

};<br />

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

wildMaineBlueberry.heavyCream.toString();<br />

// "1,cup,Organic Valley"<br />

WildMaineBlueberry.toString();<br />

// "function (blueberries, vanilla) { this.blueberries = [2, "cup", blueberries ? blueberries<br />

: "fresh wild Maine blueberries"]; this.vanilla = [1, "bean", vanilla ? vanilla : "Madagascar<br />

Bourbon"]; }"<br />

203

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

Saved successfully!

Ooh no, something went wrong!