0

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

James Cadd
  • 12,136
  • 30
  • 85
  • 134

1 Answers1

1

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.
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thank you for the explanation, that behavior was very unexpected to me. I'm tempted to never use "new" as it doesn't really do what it's generally meant to do in other languages and can be misleading. – James Cadd Aug 22 '13 at 18:31
  • @JamesCadd: It depends where you're using `new`. There is nothing wrong with using `new` for your own constructor functions. – SLaks Aug 22 '13 at 19:02
  • Thanks, I see that now. New makes fine sense when used with your own constructor functions but otherwise likely doesn't do what I intent. Have read a good bit of the Annotated ES5 link you posted and it's quite helpful. – James Cadd Aug 23 '13 at 17:56
  • @JamesCadd - You might want to look at JavaScript's powerful prototypal inheritance capabilities. See http://stackoverflow.com/questions/1450582/classical-vs-prototypal-inheritance/18023164#18023164 – Eric Elliott Sep 10 '13 at 08:34
  • @JamesCadd: See also http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Sep 10 '13 at 13:27