The line:
var bar = new Object( foo );
In your first snippet, it doesn't do anything -you are right with your assumption-, it will simply return a reference to the same object passed to the Object
constructor.
That's the behavior when you pass a native object to the Object
constructor in a new
expression (new Object(value)
), if you pass a host object, the results are implementation dependent.
If you don't pass a value (or you explicitly pass the primitives undefined
or null
) a new object that inherits from Object.prototype
will be created.
Otherwise, if you pass any of the remaining primitives (as a Number, String or a Boolean value), a primitive wrapper object will be created (basically "primitive-to-object" type conversion), for example.
var s = new String("foo"); // a string object wrapper
typeof s; // "object"
s.valueOf(); // "foo"
See this question about primitives and objects: How is a Javascript string not an object?
In your second snippet, the line:
var bar = Object.create( foo );
Creates a new object, that inherits from foo
, and since it's a different object, when you assign the properties:
bar.three = 3;
bar.one = 100;
Those will be created physically on that separated instance, as you can see, the bar.one
property shadows the value contained in foo
.
The object referenced by bar
, in fact will contain two own properties (one
and three
, but since it inherits from foo
, the property named two
is resolvable through the prototype chain, for example:
bar.hasOwnProperty('one'); // true, the property is "own"
bar.hasOwnProperty('two'); // false, the property is "inherited" from foo
bar.two; // 2, is accessible
Basically, the prototype chain of bar
looks like this:
-----------------
========> | Object.prototype| ==> null
| -----------------
|-------------| [[Prototype]] |---------|
| one: 100 | ====================> | one: 1 | (shadowed)
| three: 3 | | two: 2 |
|-------------| |---------|
(== line denotes the prototype chain)