Understanding the Prototype Chain in JavaScript

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

 true

Recall the hasOwnProperty() method.



javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.