Open In App

Understanding the Prototype Chain in JavaScript

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

When you started learning to program, you would have encountered the term object-oriented programming. Here we discover what it meant and you acknowledged that it is for grouping data into “objects” with attributes. The keyword that creates these objects in many programming languages is class. You define a category with a constructor and a number of other public and personal functions. If you would like one class to inherit from another, you write simple inheritance syntax. You have created a sequence of inheritance. Until ES2015, the language didn’t implement a category. Instead, they used the prototype chain. The new ES6 “class” hides the inner workings of the prototype chain. Understanding how the prototype chain works is crucial if you would like to develop performant code while using JavaScript’s OOP paradigm. For those familiar (or not so familiar) with computing, the prototype chain may be a linked list. It’s a gross oversimplification.

How do we initialize our chain? All objects in JavaScript have a prototype. An object’s prototype is also considered to be an object.

javascript




function Dog(name) {
  this.name = name;
}


Because a prototype is an object, a prototype has its own prototype. In that case, the prototype of Dog.prototype is Object.prototype

javascript




<script type="text/javascript" charset="utf-8">
    function Dog(name) {
      this.name = name;
    }
    console.log(
        Object.prototype.isPrototypeOf(Dog.prototype)); // yields true
</script>


Output:

 true

Recall the hasOwnProperty() method.

javascript




<script type="text/javascript" charset="utf-8">
    function Dog(name) {
      this.name = name;
    }
    let duck = new Dog("Donald");
    console.log(duck.hasOwnProperty("name")); // yields true
</script>


Output:

  true

The hasOwnProperty() method is defined in Object.prototype, which can be accessed by Dog.prototype, which can then be accessed by variable “duck”. It clearly explains the prototype chain. In this prototype chain, “Dog” is the supertype for “duck”, while “duck” is the subtype. The object is a supertype for both “Dog” and “duck”. We take an Object as a supertype for all objects in JavaScript. Any object can use the hasOwnProperty() JavaScript method.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads