↑
Main Page
Reference Types
Usage
Result
Number(false)
0
Number(true)
1
Number(undefined)
NaN
Number(null)
0
Number(“5.5”)
5.5
Number(“56”)
56
Number(“5.6.7”)
NaN
Number(new Object())
NaN
Number(100)
100
The last type cast,
String()
, is the simplest because it can accurately convert any value to a string
value. To execute the type cast, it simply calls the
toString()
method of the value that was passed in,
which converts 1 to “1”, true to “true”, false to “false”, and so on. The only difference between type cast-
ing as a string and using
toString()
is that the type cast can produce a string for a
null
or
undefined
value without error:
var s1 = String(null); //”null”
var oNull = null;
var s2 = oNull.toString(); //won’t work, causes an error
Type casting is very helpful when dealing with the loosely typed nature of ECMAScript, although you
should ensure that only proper values are used.
Reference Types
Reference types are commonly referred to as
classes
, which is to say that when you have a reference
value, you are dealing with an object. The vast number of predefined ECMAScript reference types are
discussed throughout the book. For now, the discussion focuses around the reference types that are
closely related to the primitive types just discussed.
ECMAScript doesn’t actually have classes in the traditional sense. In fact, the word “class” doesn’t
appear in ECMA-262 except to explain that there are no classes. ECMAScript defines “object defini-
tions” that are logically equivalent to classes in other programming languages. This book chooses to use
the term “class” because it is more familiar to most developers.
Objects are created by using the
new
operator and providing the name of the class to instantiate. For
example, this line creates an instance of the Object class:
var o = new Object();
25
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 25
Free JavaScript Editor
Ajax Editor
©
→ R7