Search code examples
javascriptprototype

How do I know when the prototype chain ends?


In the first case, the prototype chain is longer than in the second one.

function Func() {};
Func.__proto__ == Function.prototype; //true
Func.__proto__.__proto__ == Object.prototype; //true
Func.__proto__.__proto__.__proto__ == Object.prototype; //false
Func.__proto__.__proto__.__proto__.__proto__ == Object.prototype; //Cannot read property '__proto__' of null

In the second case, it's shorter.

let obj = {};
    obj.__proto__ == Object.prototype; //true
    obj.__proto__.__proto__ == Object.prototype; //false
    obj.__proto__.__proto__.__proto__ == Object.prototype; //Cannot read property '__proto__' of null

Why? The line of the second example obj .__ proto __.__ proto__ == Object.prototype gives false. But in the first case, the similar line of code Func .__ proto __.__ proto__ == Object.prototype gives true.

What's the difference? Why does the first example have longer prototype chain than the second one? What does it depend on?


Solution

  • Functions are also Objects in Javascript. Thinking of it as levels, they are one level below Object in the chain/tree.

    So if any function is defined, its __proto__ will be Function.prototype. Function.prototype's __proto__ will be Object.prototype.

    Note: When we do let obj ={}, under the hood obj is created as an instance of Object. Any instance of Object will have its __proto__ set to Object.prototype.