Search code examples
javascriptprototype

Why is ob.constructor.prototype == ob.__proto__


Say if we create an object

var ob = {}

When I check

ob.constructor.prototype == ob.__proto__ 

both are same how is it possible?


Solution

  • ob is a plain object, so its constructor (that is, obj.constructor) is Object. The __proto__ points to the internal prototype of something, and the internal prototype of a plain object is Object.prototype.

    If you're somewhat familiar with prototypal inheritance, the behavior might be more understandable if ob was created with new (just to see how it works - you shouldn't actually use new Object):

    var ob = new Object();
    console.log(ob.constructor.prototype == ob.__proto__);
    // same as
    console.log(ob.constructor.prototype == Object.prototype);
    // same as
    console.log(Object.prototype == Object.prototype);

    The same sort of behavior can be seen for anything created with new - its constructor.prototype will be its __proto__:

    class Foo {}
    
    const f = new Foo();
    
    console.log(f.constructor.prototype == f.__proto__);
    // same as
    console.log(f.constructor.prototype == Foo.prototype);
    // same as
    console.log(Foo.prototype == Foo.prototype);