Search code examples
javascriptprototype-programming

Where is __proto__ declared in Javascript?


Consider this example:

var a = {}
a.b =5
a.hasOwnProperty("b") // return True
a.hasOwnProperty("__proto__") // returns False

If __proto__ itself isn't declared as object's own property then,

  1. where is this __proto__ property declared ?
  2. how is this property referenced while searching through prototype chain, if it itself is not object's own property ?

Solution

  • The __proto__ property belongs to Object.prototype declared in prototype object of Object and is not own property of object a in your code. That's why it returned false when you did.

    a.hasOwnProperty("__proto__") // returns False
    

    If you do:

    console.log(Object.prototype.hasOwnProperty("__proto__")) // returns true
    

    This returns true, because __proto__ is own property of Object.prototype

    console.log(Object.prototype.hasOwnProperty("__proto__")) 

    ** Part 2:**

    The __proto__ property is a simple accessor property on Object.prototype consisting of a getter and setter function. A property access for __proto__ that eventually consults Object.prototype will find this property, but an access that does not consult Object.prototype will not. If some other __proto__ property is found before Object.prototype is consulted, that property will hide the one found on Object.prototype.

    That's how it finds its way in the prototype chain.