日期:2014-05-16  浏览次数:20273 次

JavaScript ---- Wrapper Objects
We've also seen that strings have properties and methods:
     var s = "hello world!";        // A string
     var word = s.substring(s.indexOf(" ")+1, s.lenght);    // Use string properties
Strings are not objects, though, so why do they have properties? Whenever you try to refer to a property of a string s, JavaScript converts the string value to an object as if by calling new String(s).This object inherits string methods and is used to resolve the property reference. Once the property has been resolved, the newly created object is discarded.

Numbers and booleans have methods for the same reason that strings do: a temporary object is created using the Number() or Boolean() constructor, and the method is resolved using the temporary object.

There are not wrapped objects for the null and undefined values: any attempt to access a property of one of these values causes a TypeError.

The temporary objects created when you access a property of a string, number, or boolean are known as wrapped objects, and it may occasionally be necessary to distinguish a string value from a String object or a number or boolean value from a Number or Boolean object.

Note that it is possible (but almost never necessary or useful) to explicitly create wrapper objects, by invoking the String(), Number(), or Boolean() constructors:
     var s = "test", n = 1, b = true;        // A string, number, and boolean value.
      var S = new String(s);                  // A String object
      var N = new Number(n);                  // A Number object
      var B = new Boolean(b);                 // A Boolean object