No, not everything is an object in JavaScript. Many things that you interact with regularly (strings, numbers, booleans) are primitives, not objects. Unlike objects, primitive values are immutable. The situation is complicated by the fact that these primitives do have object wrappers (String
, Number
and Boolean
); these objects have methods and properties while the primitives do not, but the primitives appear to have methods because JavaScript silently creates a wrapper object when code attempts to access any property of a primitive.
For example, consider the following code:
var s = "foo";
var sub = s.substring(1, 2); // sub is now the string "o"
Behind the scenes, s.substring(1, 2)
behaves as if it is performing the following (approximate) steps:
- Create a wrapper
String
object from s
, equivalent to using new String(s)
- Call the
substring()
method with the appropriate parameters on the String
object returned by step 1
- Dispose of the
String
object
- Return the string (primitive) from step 2.
A consequence of this is that while it looks as though you can assign properties to primitives, it is pointless because you cannot retrieve them:
var s = "foo";
s.bar = "cheese";
alert(s.bar); // undefined
This happens because the property is effectively defined on a String
object that is immediately discarded.
Numbers and Booleans also behave this way. Functions, however, are fully-fledged objects, and inherit from Object
(actually Object.prototype
, but that's another topic). Functions therefore can do anything objects can, including having properties:
function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…