3.12. Primitive Data Type Wrapper Objects
When we discussed strings earlier in this chapter, I pointed out a strange feature of that data type: to operate on strings, you use object notation. For example, a typical operation involving strings might look like the following:
var s = "These are the times that try people's souls."; var last_word = s.substring(s.lastIndexOf(" ")+1, s.length);
If you didn't know better, it would appear that s was an object and that you were invoking methods and reading property values of that object.
What's going on? Are strings objects, or are they primitive data types? The typeof operator (see Chapter 5) assures us that strings have the data type "string", which is distinct from the data type "object". Why, then, are strings manipulated using object notation?
Note that the String object created when we use a string in an object context is a transient one -- it is used to allow us to access a property or method and then is no longer needed, so it is reclaimed by the system. Suppose s is a string and we determine the length of the string with a line like this:
var len = s.length;
If we want to use a String object explicitly in our program, we have to create a nontransient one that is not automatically discarded by the system. String objects are created just like other objects, with the new operator. For example:
var s = "hello world"; // A primitive string value var S = new String("Hello World"); // A String object
msg = S + '!';
Copyright © 2003 O'Reilly & Associates. All rights reserved.