Your question has already been satisfactorily answered by Squeegy - it has nothing to do with objects and primitives, but with the reassignment of variables and property settings in the same reference object.
The answers and comments have a lot of confusion regarding JavaScript types, so here is a small introduction to a system like JavaScript:
JavaScript has two fundamentally different kinds of values: primitives and objects (and there is no such thing as a hash).
Strings, numbers and Booleans, as well as null and undefined are primitives, objects are all that can have properties. Even arrays and functions are regular objects and therefore can contain arbitrary properties. They simply differ in the internal property [[Class]] (functions additionally have a property called [[Call]] and [[Construct]], but hey, these details).
The reason primitive values ββcan behave like objects is related to autoboxing, but the primitives themselves cannot contain any properties.
Here is an example:
var a = 'quux'; a.foo = 'bar'; document.writeln(a.foo);
This will exit undefined : a contains the primitive value that is assigned to the object when the foo property is assigned. But this new object is immediately discarded, so the value of foo is lost.
Think of it this way:
var a = 'quux'; new String(a).foo = 'bar'; // we never save this new object anywhere! document.writeln(new String(a).foo); // a completly new object gets created
Christoph Feb 04 '09 at 1:44 2009-02-04 01:44
source share