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.

C H A P T E R 2<br />

■ ■ ■<br />

Type Conversion<br />

Iron Man, Superman, Batman, Spider-Man, X-Men, and countless other superheroes have many traits in<br />

common. Most have a distinctive costume, unwavering morals, underlying motif, secret identity,<br />

supervillains to fight, and, of course, extraordinary powers. Those powers may or may not be innate,<br />

though. For example, Clark Kent doesn’t need his Superman costume to fly, but Tony Stark would drop<br />

like a stone without his Iron Man armor.<br />

JavaScript values of object type or array and function subtypes are like Superman or Spider-Man.<br />

They innately have extraordinary powers, referred to as members or methods. On the other hand, values<br />

of the string, number, or boolean type are like Iron Man or Batman in that they need to put on their<br />

costume, referred to as a wrapper, to have extraordinary powers.<br />

So, just as seeing the bat signal appear in the night sky over Gotham City tells Bruce Wayne to put on<br />

the bat suit in order to become Batman, seeing the . operator appear to their right tells a string, number,<br />

or boolean to put on a wrapper in order to become an object.<br />

Conversely, just as Batman returns to being Bruce Wayne after defeating the Joker, Penguin, or<br />

Catwoman, a wrapper object returns to being a string, number, or boolean after invoking a method. To<br />

convert a string, number, or boolean to a wrapper object, JavaScript invokes String(), Number(), or<br />

Boolean(). Those are referred to as constructor functions. To reverse the conversion, that is, to convert a<br />

wrapper object back to a string, number, or boolean, JavaScript invokes valueOf() on the wrapper.<br />

Insofar as JavaScript converts string, number, and boolean values to and from wrapper objects<br />

behind the scenes, we just need to explore their features. Moreover, string wrappers are useful, but those<br />

for numbers and booleans are not. So, we won’t waste time on those.<br />

String Members<br />

Open firebug.html in Firefox, and then press F12 to enable Firebug. If you’re just joining us, flip back to<br />

the preface for details on how to do this. In Chapter 1, you learned how to glue one string to another with<br />

the + operator. concat() does the same thing. So in Firebug, let’s glue "man" to "Bat" by way of the +<br />

operator and concat() method, verifying our work with Figure 2–1:<br />

"Bat" + "man";<br />

// "Batman"<br />

"Bat".concat("man");<br />

// "Batman"<br />

25

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

Saved successfully!

Ooh no, something went wrong!