Given the following code sample:
var base = {
one: "one",
two: 2,
test: function() { return "test"; }
};
var derived1 = new Object(base);
function Ctor() { };
Ctor.prototype = base;
var derived2 = new Ctor();
var proto1 = Object.getPrototypeOf(derived1);
var proto2 = Object.getPrototypeOf(derived2);
var isProto1Base = proto1 === base;
var isProto2Base = proto2 === base;
I had expected both isProto1Base and isProto2Base to be true. However, isProto1Base === false and isProto2Base === true. Why is that?
EDIT: Fixed title to reflect code
new Object(base)
is not the same as Object.create(base)
.
new Object(x)
will box x
into an object.
In particular, new Object(base) === base
is true.
For more detail, see the spec:
- If value is supplied, then
- If Type(value) is Object, then
- If the value is a native ECMAScript object, do not create a new object but simply return value.