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

204<br />

Figure 6–7. Native JavaScript constructors defined by ECMAScript or DOM always override<br />

Object.prototype.toString().<br />

Testing for an Array<br />

To test for arrayness like Array.isArray() in ECMAScript 5 dummies like Explorer 8, we need to<br />

circumvent any toString() method overriding Object.prototype.toString() to avoid the gluey string<br />

that JavaScript shows us when we call toString() on an array. Having done so, we would then return<br />

true if Object.prototype.toString() returns "[object Array]" and false if not.<br />

ECMAScript defines a couple of methods for function values, apply() and call(), that provide a way<br />

to borrow a method like Object.prototype.toString() and use it as if it were inherited (so we have<br />

access to it over the head of any overridden methods).<br />

The first parameter to apply() or call() is an object to bind to this for the method you are<br />

borrowing. If you wanted to invoke Object.prototype.toString() on [1, "cup", "Organic Valley"],<br />

which is to say circumvent Array.prototype.toString(), you’d pass [1, "cup", "Organic Valley"] as<br />

the first parameter to apply() or call(). Try both methods, verifying your work with Figure 6–8. Note<br />

that, to save some typing, you can just replace Object.prototype with an empty object literal wrapped in<br />

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

Object.prototype.toString.apply(wildMaineBlueberry.halfHalf);

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

Saved successfully!

Ooh no, something went wrong!