Java Reference
In-Depth Information
This is where JavaScript helps you out. Recall from previous chapters that JavaScript can handle the
conversion of one data type to another automatically. For example, if you tried to add a string primitive
to a number primitive, like this:
theResult = “23” + 23;
JavaScript would assume that you want to treat the number as a string and concatenate the two
together, the number being converted to text automatically. The variable theResult would contain
“2323” — the concatenation of 23 and 23, and not the sum of 23 and 23, which would be 46.
The same applies to objects. If you declare a primitive string and then treat it as an object, such as by
trying to access one of its methods or properties, JavaScript will know that the operation you're trying
to do won't work. The operation will only work with an object; for example, it would be valid with a
String object. In this case, JavaScript converts the plain-text string into a temporary String object, just
for that operation, and destroys the object when it's fi nished the operation.
So, for your primitive string mySecondString, you can use the length property of the String object
to fi nd out the number of characters it contains. For example:
var lengthOfSecondString = mySecondString.length;
This would store the data 22 in the variable lengthOfSecondString.
The same ideas expressed here are also true for number and Boolean primitives and their corresponding
Number and Boolean objects. However, these objects are not used very often, so we will not be discuss-
ing them further in this topic.
JavaScript's Native Object Types
So far, you have just been looking at what objects are, how to create them, and how to use them. Now
take a look at some of the more useful objects that are native to JavaScript — that is, those that are built-
in to the JavaScript language.
You won't be looking at all of the native JavaScript objects, just some of the more commonly used ones,
namely the String object, the Math object, the Array object, and the Date object. Later in the topic, a
whole chapter is devoted to each of the more complex objects, such as the String object (Chapter 9)
and the Date object (Chapter 10).
String Objects
Like most objects, String objects need to be created before they can be used. To create a String object,
you can write this:
var string1 = new String(“Hello”);
var string2 = new String(123);
var string3 = new String(123.456);
Search WWH ::




Custom Search