Skip to main content

Command Palette

Search for a command to run...

JavaScript Prototype Inheritance Explained Through Cooking

Updated
4 min read
JavaScript Prototype Inheritance Explained Through Cooking

Javascript’s prototype-based inheritance system can be confusing at first, especially if you’re coming from a class-based language like Java or C++. But don’t worry. I got you covered. We’re going to break it down using something we all understand : cooking. 🍳

Just like in the kitchen ,where recipes get passed down and modified over time, javascript objects inherit properties and behaviours from their prototypes. Let’s dive in and make sense of this concept using a fun and relatable cooking analogy!

🍽️ What is Prototype Inheritance?

Imagine you’re a chef running a restaurant. You have a base recipe for a dish, and each chef in your kitchen follows that recipe but can tweak it to add their own style.

In Javascript, objets inherits properties from a shared prototype, just like all chefs in your kitchen rely on the base recipe. This is different from class-based inheritance (like in java) , where each new dish would be a completely separate copy of an original.

Prototype vs Classical Inheritance:

  • Classical Inheritance (Other languages) : Think of a handwritten cookbook where each dish is fully copied into different editions of the book. Any changes to one book don’t affect others.

  • Prototype Inheritance (Javascript) : Imagine a master recipe that all chefs refer to. If the master recipe changes, all dishes using it automatically get updated.

🔍 Prototype vs __proto__: Understanding the Difference

You may have seen both prototype and __proto__ in Javascript and wondered how they relate. Let’s explain it with cooking analogy.

🍳 Prototype Property (prototype)

This is like the original cookbook containing all base recipes. It defined shared properties and methods that all derived recipes(Objets) can access.

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

Recipe.prototype.cook=functon(){
    console.log(`Cooking ${this.name} using the standard recipe.`);
}

🍲 __proto__ Property ([[Prototype]])

Each objets has a __proto__ ,which acts like a the personalized chef notebook that link back to the main cookbook. This allows individual chefs(objects) to refer to the master recipe if they don’t have their own version.

const pasta =new Recipe('Pasta')
console.log(pasta.__proto__ === Recipe.prototype)

Output will be true for above.

Visualizing the Relationship:

Recipe.prototype  <-- Master Cookbook (Shared among all chefs)
  |
  v
pasta.__proto__   <-- Chef's Notebook (Links to Master Cookbook)

🏗️ The new Keyword and Constructor Functions

When you use the new keyword, you’re creating a new dish based on a recipe template(constructor function)

For Example : Creating Dishes from Recipes

function Dish(name,cuisine){
    this.name=name;
    this.cuisine=cuisine;
}

Dish.prototype.describe=function(){
    console.log(`${this.name} is a delicious ${this.cuisine} dish. `)
}

const pizza=new Dish("Pizza", "Italian");
pizza.describe();

Output will be “ Pizza is a delicious Italian dish. “ for above.

Behind the Scenes: How __proto__ is Set

When new Dish(“Pizza”, “Italian”) runs , Javascript:

  1. Creates a new object.

  2. Sets its ___proto__ to Dish.prototype

  3. calls the Dish constructor with this referring to the new object.

🔄 Inheritance Without extends

Javascript allows inheritance wven without using class and extends, thanks to Object.create()

🍛 Example: Creating Variations of a Dish

const baseRecipe={
    cook:function(){
        console.log(`Cooking ${this.name} using the traditional methods.`);
    }
}

const sushi=Object.create(baseRecipe);
sushi.name="Sushi"
sushi.cook();

Here, sushi inherits from baseRecipe, just like a chef making slight modifications to a base dish!

Official doc :

🔥 Events in JavaScript Through Cooking Analogies

JS’s event system works just like a well-organized kitchen: timers go off , ingredients mix, and everything flows smoothly.

🍜 Example: Timers and Cooking

console.log("start Cooking")
setTimeout(()=> console.log("Ding! The oven time is done.),3000);
console.log("Preparing side dishes")

Output of above code:

Start Cooking
Preparing side dishes
Ding ! The oven timer is done.

Even through the timer was set first, it executes last, just like a real kitchen where dishes cook while you prepare other items.

🔥 Pitfalls and Best Practices

just like a cooking, prototype inheritance comes with some pitfalls:

❌ Overwriting Prototypes Can Be Dangerous

Dish.prototype={
    newMethod(){
        console.log("OverWritten")
    }
}

This replaces the entire prototype, breaking any existing inheritance.

✅ Best Practice: Modify Instead

Dish.prototype.newMethod=function(){
    console.log("Safely added a new method")
}

🍽️ Wrapping Up

  • Prototype inheritance is like chefs sharing and modifying recipes.

  • Prototype (prototype) is the master cookbook

  • __proto__ is a personal chef’s notebook referring to the master cookbook

  • The new keyword creates a new dish from a recipe template.

  • Object.create() allows inheritance without class.

  • JS events work like timers and workflows in a kitchen.

Understanding prototype inheritance is key to mastering Javascript, and the right cooking analogy, it can be easier to digest.

17 views

More from this blog

Ajay Patel

116 posts

JavaScript Prototype Inheritance Explained Through Cooking