Search code examples
javascriptprototype-programming

Does a new object in Javascript have a prototype property?


This is a purely trivial question for academic value:

If I create a new object, either by doing:

var o = { x:5, y:6 };

or

var o = Object.create({ x:5, y:6 });

when I query the o.prototype property, I get undefined. I thought that any newly created object automatically inherits the Object.prototype prototype.

Furthermore, invoking toString(), (a method of Object.prototype) on this object works just fine, implying that o does inherit from Object.prototype. So why do I get undefined?


Solution

  • There is a difference between instances and their constructors.

    When creating an object like {a: 1}, you're creating an instance of the Object constructor. Object.prototype is indeed available, and all functions inside that prototype are available:

    var o = {a: 1};
    o.hasOwnProperty === Object.prototype.hasOwnProperty; // true
    

    But Object.create does something different. It creates an instance (an object), but inserts an additional prototype chain:

    var o = {a: 1};
    var p = Object.create(o);
    

    The chain will be:

    Object.prototype  -  o  -  p
    

    This means that:

    p.hasOwnProperty === Object.prototype.hasOwnProperty; // true
    p.a === o.a; // true
    

    To get the prototype "under" an instance, you can use Object.getPrototypeOf:

    var o = {a: 1};
    var p = Object.create(o);
    
    Object.getPrototypeOf(p) === o; // true
    Object.getPrototypeOf(o) === Object.prototype; // true
    

    (Previously, you could access an instance's prototype with o.__proto__, but this has been deprecated.)

    Note that you could also access the prototype as follows:

    o.constructor === Object; // true
    

    So:

    o.constructor.prototype === Object.prototype // true
    o.constructor.prototype === Object.getPrototypeOf(o); // true
    

    This fails for Object.create-created objects because they do not have a constructor (or rather, their constructor is Object and not what you passed to Object.create because the constructor function is absent).