Wrapper Objects
JavaScript objects are composite values: they are a collection
of properties or named values. We refer to the value of a property
using the . notation. When the
value of a property is a function, we call it a
method. To invoke the method m of an object o, we write o.m().
We’ve also seen that strings have properties and methods:
vars="hello world!";// A stringvarword=s.substring(s.indexOf(" ")+1,s.length);// Use string properties
Primitive 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 (see Inheritance) string methods and is used to resolve the
property reference. Once the property has been resolved, the newly
created object is discarded. (Implementations are not required to
actually create and discard this transient object: they must behave as
if they do, however.)
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 that temporary object. There are no wrapper objects for
the null and undefined values: any attempt to access a
property of one of these values causes a TypeError.
Consider the following code and think about what happens when it is executed:
vars="test";// Start with a string value.s.len=4;// Set a property on it.vart=s.len;// Now query the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access