Why is that this code:
var foo = {one: 1, two: 2};
var bar = new Object( foo );
bar.three = 3;
bar.one = 100;
document.write(bar.one); //100
document.write(foo.one); //100
results in bar.one & foo.one being both 100, while
var foo = {one: 1, two: 2};
var bar = Object.create( foo );
bar.three = 3;
bar.one = 100;
document.write(bar.one); //100
document.write(foo.one); //1
only affects bar.one..
My first intuition is that since in the first piece of code we are assigning a foo reference to bar, then it means the change will also apply to foo, while on the second code, it probably ‘inherits’ from foo, and therefore the change on bar’s ‘subclass’ attribute won;t apply to its ‘superclass’ (prototype)..
Can somebody please confirm that my assumption is at least on the right track? Would absolutely appreciate any answers. Thanks in advance.
The line:
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
Objectconstructor.That’s the behavior when you pass a native object to the
Objectconstructor in anewexpression (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
undefinedornull) a new object that inherits fromObject.prototypewill 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.
See this question about primitives and objects: How is a Javascript string not an object?
In your second snippet, the line:
Creates a new object, that inherits from
foo, and since it’s a different object, when you assign the properties:Those will be created physically on that separated instance, as you can see, the
bar.oneproperty shadows the value contained infoo.The object referenced by
bar, in fact will contain two own properties (oneandthree, but since it inherits fromfoo, the property namedtwois resolvable through the prototype chain, for example:Basically, the prototype chain of
barlooks like this:----------------- ========> | Object.prototype| ==> null | ----------------- |-------------| [[Prototype]] |---------| | one: 100 | ====================> | one: 1 | (shadowed) | three: 3 | | two: 2 | |-------------| |---------| (== line denotes the prototype chain)