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 2 ■ TYPE CONVERSION<br />

56<br />

Figure 2–31. JavaScript does not set the i, g, or m flag when converting a string to a RegExp object.<br />

Summary<br />

In this chapter, you learned that JavaScript converts a string to a wrapper object whenever the string is<br />

the left operand to the . or [] operator, quietly passing the string to the String() constructor and then<br />

just as quietly reverting the wrapper to a string by invoking its valueOf() method. String wrappers<br />

manipulate characters as if they were read-only elements. In other words, string values are immutable,<br />

and wrapper methods return a new value without changing the original. So, typically you will want to<br />

save the return value or immediately pass it to one of the operators we’ll explore in Chapter 3.<br />

Most JavaScript operators are particular about the value type of their operands. Knowing this,<br />

JavaScript will save the day by converting an operand of the wrong type to the correct one. Though<br />

JavaScript does so behind the scenes, we explored how to do so by passing values to String(), Number(),<br />

Boolean(), and Object(). If invoked without the new operator, those constructors convert their argument<br />

to a string, number, boolean, or object. So, a string can be converted to a wrapper by passing it to<br />

Object() without new or to String() with new:<br />

Object("Spider-Man");<br />

new String("Spider-Man");<br />

So, when JavaScript creates a wrapper for a string, it’s really converting the value from the string<br />

type to the object type. The same thing goes for number or boolean wrappers, too. Therefore, value type<br />

conversion is vital for manipulating values with wrapper methods or with operators. You’ll learn more<br />

about the latter in Chapter 3. Take a breather, and I’ll see you there!

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

Saved successfully!

Ooh no, something went wrong!