04.11.2015 Views

javascript

Create successful ePaper yourself

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

Chapter 3: Language Basics<br />

If you ’ re not sure that a value isn ’ t null or undefined , you can use the String() casting function,<br />

which always returns a string regardless of the value type. The String() function follows these rules:<br />

❑<br />

❑<br />

❑<br />

If the value has a toString() method, it is called (with no arguments) and the result is<br />

returned.<br />

If the value is null , “null” is returned.<br />

If the value is undefined , “undefined” is returned.<br />

Consider the following:<br />

var value1 = 10;<br />

var value2 = true;<br />

var value3 = null;<br />

var value4;<br />

alert(String(value1)); //”10”<br />

alert(String(value2)); //”true”<br />

alert(String(value3)); //”null”<br />

alert(String(value4)); //”undefined”<br />

Here, four values are converted into strings: a number, a Boolean, “null” , and “undefined” . The result<br />

for the number and the Boolean are the same as if toString() were called. Because toString() isn ’ t<br />

available on “null” and “undefined” , the String() method simply returns literal text for those<br />

values.<br />

The Object Type<br />

Objects in ECMAScript start out as nonspecific groups of data and functionality. Objects are created by<br />

using the new operator followed by the name of the object type to create. Developers create their own objects<br />

by creating instances of the Object type and adding properties and/or methods to it, as shown here:<br />

var o = new Object();<br />

This syntax is similar to Java, although ECMAScript requires parentheses to be used only when<br />

providing arguments to the constructor. If there are no arguments, as in the following example, then the<br />

parentheses can be omitted safely (though that ’ s not recommended):<br />

var o = new Object; //legal, but not recommended<br />

Instances of Object aren ’ t very useful on their own, but the concepts are important to understand<br />

because, similar to java.lang.Object in Java, the Object type in ECMAScript is the base from which<br />

all other objects are derived. All of the properties and methods of the Object type are also present on<br />

other, more specific objects.<br />

Each Object instance has the following properties and methods:<br />

❑<br />

constructor — The function that was used to create the object. In the previous example, the<br />

constructor is the Object() function.<br />

40

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

Saved successfully!

Ooh no, something went wrong!