Skip to content
Related Articles

Related Articles

Understanding the Prototype Chain in JavaScript
  • Last Updated : 22 Jul, 2020

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 the 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 the 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.




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




// Returns true
Object.prototype.isPrototypeOf(Dog.prototype);

Output:

 true

Recall the hasOwnProperty() method.



javascript




let duck = new Dog("Donald");
duck.hasOwnProperty("name"); // yields true

Output:

  true

The hasOwnProperty() method is defined in Object.prototype, that 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 is a supertype for all objects in JavaScript. Any object can use the hasOwnProperty() JavaScript method.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :