Skip to content

JavaScript prototype chain | Simple

  • by

In JavaScript, every object has a prototype, including the prototype object. This “chain” goes all the way back until it reaches an object that has no prototype, usually Object‘s a prototype. Because each object has a private property that holds a link to another object that’s why it is called a prototype chain in JavaScript.

function Dog(name) {
  this.name = name;
}
Object.prototype.isPrototypeOf(Dog.prototype);

The prototype is basically a property of a JavaScript function. The prototype’s version of “Inheritance” involves adding another link to the end of this prototype chain, as shown above.

JavaScript prototype chain

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const myObject = {
      city: 'Madrid',
      greet() {
        console.log(`Greetings from ${this.city}`);
      }
    }

    myObject.greet();
    console.log(myObject.toString())
  </script>
</body>
</html> 

Output:

JavaScript prototype chain

Read more: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes

  • When you access a property or method on an object, JavaScript first checks if the object itself has that property or method. If it doesn’t find it, it looks up the prototype chain.
  • JavaScript will continue to follow the __proto__ chain until it finds the property or method or reaches the end of the chain.

Do comment if you have any doubts or suggestions on this JS prototype topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading