Search code examples
javascriptprototype

Why does Object._proto_ refer to Function.prototype?


I am looking at this diagram below in the relationship between objects and functions and I am wondering why the Object.proto refers to Function.prototype?

enter image description here


Solution

  • __proto__ refers to an object's immediate prototype ancestor. For a simple example obj is the immediate ancestor of obj2:

    let obj = {}
    // make obj2 with obj parent
    let obj2 = Object.create(obj)
    obj === obj2.__proto__ // true
    

    In the case of your diagram, it is showing the prototype chain from a function to the Function.prototype to the Object.prototype. You can follow it like a chain:

    function test(){}
    
    console.log(test.__proto__ === Function.prototype)
    console.log(test.__proto__.__proto__ === Object.prototype)
    
    // alternatively:
    Object.getPrototypeOf(test) // Function.prototype

    In your example Object.__proto__ is the Function.prototype because Object is a contructor function in the same way String and Number are functions. But this isn't the same thing as Object.prototype which is the object other object's __proto__ property point to:

    console.log (Object)
    console.log(typeof Object)
    
    // call the function to create an object
    let o = Object()
    // o's prototype is the Object prototype
    console.log (o.__proto__ === Object.prototype)