Search code examples
javascriptjqueryprototypeprototypal-inheritance

JavaScript prototype property and prototype link


I understand JavaScript prototype. But I get confused with the difference between prototype property and hidden prototype link. Also, what is the difference between Object prototype link and Function prototype link ?

I am seeking a very basic example to demonstrate the same (mainly the prototype link/chaining, like how it looks up for the property in terms of both Object prototype link and Function prototype link).


Solution

  • Document Object Model(DOM) is a beautiful example of inheritance in JavaScript.

    Imagine you have a div. It's an instance of HTMLDivElement.

    var div = document.createElement('div');
    
    div instanceof HTMLDivElement; // -> true
    
    div instanceof HTMLElement; // -> true
    
    div instanceof Element; // -> true
    
    div instanceof Object; // -> true
    

    div is an Object and includes all methods and properties that is in HTMLDivElement.prototype. It's under __proto___ property but it doesn't mean you should do div.__proto__.insertBefore to access insertBefore. It's like an include in other languages.

    In other words div.__proto__ is pointing to HTMLDivElement.prototype.

    prototype is an Object. Because of that, it can have it's own __proto__ pointer. In this Case HTMLDivElement's prototype is an Object and have a __proto__ that is pointing to HTMLElement.prototype, so it includes all methods and properties. It goes down this path until Object.prototype that doesn't have a __proto__ pointer and lookup stups.

    I tried to avoid using new keyword for explaining this. I hope it helps...