0

I tried the following code snippet:

var man = new Object();
man = {sex : 'male'}
var child = new Object(man);
child.firstName = 'foo'
child.lastName = 'bar'
Object.getPrototypeOf(child);

This returns Object {}, while I expected it to return the object associated with man. However, this snippet:

var man = Object.create(null);  
man = {sex : 'male'}
var child = Object.create(man);  
child.firstName = 'foo'  
child.lastName  = 'bar'

Object.getPrototypeOf(child);

It does return the object associated with man. Conceptually, where am I going wrong?

Projjol
  • 1,195
  • 2
  • 12
  • 26

2 Answers2

2

The reason for the difference is that is what it is specified to do. The Object constructor simply coerces its argument to an object - it does not do anything with the prototype:

When the Object constructor is called with no arguments or with one argument value, the following steps are taken:
1. If value is supplied, then
a. If Type(value) is Object, then
i. If the value is a native ECMAScript object, do not create a new object but simply return value. http://es5.github.io/#x15.2.2.1

Object.create on the other hand, sets the prototype:

  1. If Type(O) is not Object or Null throw a TypeError exception.
  2. Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name
  3. Set the [[Prototype]] internal property of obj to O.
    http://es5.github.io/#x15.2.3.5
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
1

I think the conceptual misunderstanding lies in what you think new Object() does. if you pass an object into new Object(), the new object will have whatever properties that object has. However, it does not create a new object with the prototype of the original object, it just takes each property and adds it to the newly created object.

eddyjs
  • 1,270
  • 10
  • 20