Pregunta

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

¿Fue útil?

Solución

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:

  1. If value is supplied, then
    1. If Type(value) is Object, then
      1. If the value is a native ECMAScript object, do not create a new object but simply return value.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top