Search code examples
javascriptobjectprototypal-inheritanceprototype-programming

Object prototype in JavaScript


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?


Solution

  • 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