Member-only story

The Power of Prototypal Inheritance in JavaScript

An Easier Way to Share Code Between Objects

Max N
3 min readMar 2, 2024

JavaScript is a prototype-based language, meaning object properties and methods can be shared through prototypal inheritance as opposed to class-based inheritance in other languages. This allows for more flexibility and better performance in many cases.

In this article, we’ll dive into how prototypal inheritance works in JavaScript and how you can leverage it to write cleaner, more maintainable code.

How Prototypal Inheritance Works

Every JavaScript object contains a hidden “prototype” property that links to another object. When you try to access a property on an object that doesn’t exist, the JavaScript engine will check the prototype object and then the prototype’s prototype and so on up the chain until it finds the property or reaches the end.

This linkage of objects is called the “prototype chain” and it enables objects to inherit shared properties and methods from other objects.

Here’s an example:

let person = {
name: "John",
printBio: function() {
console.log(`My name is ${this.name}`);
}
};

let me = Object.create(person);

me.name = "Mike";

me.printBio(); // logs "My name is Mike"

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet