skip to Main Content

I’ve been learning about JavaScript object inheritance and came across two terms that seem related but are a bit confusing: __proto__ and prototype.

From what I understand: __proto__ is a property found on all objects, and it points to the prototype of the object.
prototype is a property of constructor functions.
However, I’m not quite clear on the practical differences between these two and how they are used differently in JavaScript. Could someone explain the difference between __proto__ and prototype with examples? Specifically, I’m interested in understanding:

How and when to use __proto__ vs prototype.
The role each plays in the prototype chain and inheritance.
Any clarification with code examples would be greatly appreciated!

2

Answers


  1. To access the prototype of an instantiated object you can use __proto__. prototype is used to access the prototype attached to a class.

    So, accessing __proto__ on an object is the same as accessing prototype on its constructor.

    const element = document.createElement('div');
    console.log(element.__proto__ === element.constructor.prototype); // true
    
    Login or Signup to reply.
  2. Usually prototype is a property of a function. When you call a function with keyword new you create an object with the function called as a constructor and the function’s prototype becomes __proto__ property of the object. So __proto__ is a property of an object that references the function’s property prototype. In reality __proto__ is a getter/setter in Object.prototype. And it’s deprecated and Object.get/setPrototypeOf() is now recommended.

    Due dynamic nature of JS you can assign any object as a prototype.

    console.log(({}).prototype); // an object by default doesn't contain "prototype"
    console.log((function(){}).prototype); // a function by default does
    
    // __proto__ is actuall a getter/setter
    console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));
    
    function Foo(){
      // Foo.prototype is assigned automatically to __proto__ with "new" keyword 
      console.log(Object.getPrototypeOf(this)); 
      this.bar = 'bar';
    }
    
    Foo.prototype.baz = function() {console.log(this.bar)};
    
    const foo = new Foo; 
    foo.baz();
    
    // we can assign the prototype manually
    const fooHack = {bar: 'hacky bar'};
    Object.setPrototypeOf(fooHack, Foo.prototype);
    fooHack.baz();
    .as-console-wrapper{min-height:100%!important}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search