Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 8: Objects & Prototypal Inheritance

1. What is a Prototype?

In JavaScript, every object has a hidden property called [[Prototype]]. This is a reference to another object.

  • When you try to access a property on an object and JS can’t find it, it doesn’t give up immediately.
  • It looks at the object’s Prototype to see if the property exists there.

2. The Prototype Chain

This “lookup” process continues until the property is found or the chain reaches null.

  • myArray $\rightarrow$ Array.prototype $\rightarrow$ Object.prototype $\rightarrow$ null.

This is why you can use methods like .push() on an array even though you didn’t define .push() yourself—it’s inherited from the Array.prototype.


3. Creating Objects with Prototypes

A. Constructor Functions

Before ES6 classes, this was the primary way to create multiple objects of the same “type.”

JavaScript

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

// Adding a method to the Prototype (Memory Efficient)
Robot.prototype.greet = function() {
    console.log(`Beep Boop, I am ${this.name}`);
};

const r1 = new Robot("R2D2");
const r2 = new Robot("C3PO");

r1.greet(); // Works
r2.greet(); // Works

Performance Tip: We put methods on the prototype so that every instance shares one copy of the function in memory, rather than creating a new function for every single robot.

B. Object.create()

This method creates a new object and allows you to specify exactly which object should be its prototype.

JavaScript

const animal = {
    eats: true,
    walk() { console.log("Animal walking..."); }
};

const dog = Object.create(animal);
dog.bark = function() { console.log("Woof!"); };

dog.walk(); // "Animal walking..." (Inherited)
console.log(dog.eats); // true (Inherited)

4. Shadowing Properties

If you add a property to an object that has the same name as a property in its prototype, the object’s property “shadows” (overwrites) the prototype’s property for that specific instance.

JavaScript

const vehicle = { wheels: 4 };
const motorbike = Object.create(vehicle);
motorbike.wheels = 2; // Shadowing

console.log(motorbike.wheels); // 2
console.log(vehicle.wheels);   // 4 (Original remains unchanged)

5. Checking Prototypes

You can inspect the prototype relationship using these modern methods:

  • Object.getPrototypeOf(obj): Returns the prototype of obj.
  • obj.hasOwnProperty('prop'): Checks if a property belongs to the object itself or if it’s inherited.

JavaScript

console.log(dog.hasOwnProperty('bark')); // true
console.log(dog.hasOwnProperty('eats')); // false (Inherited)

6. Prototypal Inheritance vs. Classical Inheritance

FeaturePrototypal (JS)Classical (Java/C++)
FoundationObjects inherit from Objects.Classes inherit from Classes.
FlexibilityHighly dynamic; can change prototypes at runtime.Rigid; structure defined at compile time.
MemoryInstances share methods via the chain.Instances get copies or use v-tables.

💻 Technical Code Example: Extending Built-in Prototypes

Warning: Do not do this in production (it’s called “Monkey Patching”), but it’s great for understanding how JS works.

JavaScript

// Adding a custom method to the global Array prototype
Array.prototype.lastItem = function() {
    return this[this.length - 1];
};

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.lastItem()); // "Cherry"

In Simple Words :

1. Introduction

Objects are the building blocks of modern applications.
In JavaScript, objects are not copied from classes — they inherit directly from other objects using prototypes.

Understanding this module helps you master:

  • Object behavior
  • Memory sharing
  • Method reuse
  • How JavaScript actually works internally

2. What is an Object?

Definition

An object is a collection of key–value pairs, where:

  • Keys → properties
  • Values → data or functions (methods)

Example (conceptual):

user = {
  name: "Prakash",
  age: 24,
  login()
}

3. Properties & Methods

Properties

  • Store data
  • Can be primitive or reference types

Methods

  • Functions stored inside objects
  • Use this to access object data

4. Creating Objects

1. Object Literal (Most Common)

const user = { name: "A", age: 20 }

2. Using new Object()

const user = new Object()

3. Constructor Functions

function User(name) {
   this.name = name
}

4. Object.create()

Creates object with a specified prototype.

const user = Object.create(proto)

5. ES6 Classes (Syntactic Sugar)

class User {
   constructor(name) {}
}

⚠️ Internally still uses prototypes.


5. Object Property Access

  • Dot notation → user.name
  • Bracket notation → user["name"]

Use bracket when:

  • Dynamic keys
  • Special characters

6. Property Descriptors

Each property has:

  • value
  • writable
  • enumerable
  • configurable

Used to control:

  • Mutability
  • Visibility
  • Deletion

7. Object Mutability

Objects are mutable:

  • Passed by reference
  • Changes affect original object

Important for:

  • Performance
  • Bug prevention

8. What is Prototypal Inheritance?

Definition

Prototypal inheritance means:

Objects can inherit properties and methods from another object via a prototype.

No classes required.


9. The Prototype Chain

Every JavaScript object has:

  • A hidden property: [[Prototype]]
  • Accessed via __proto__ (internal)

When property not found:

  1. Search object
  2. Search prototype
  3. Continue up chain
  4. End at null

10. prototype vs __proto__

TermMeaning
prototypeProperty of constructor function
__proto__Link from object to prototype

This distinction is interview-critical.


11. Constructor Functions & Inheritance

Example flow:

new User() → User.prototype → Object.prototype → null

Methods defined on prototype are shared across instances.


12. Inheriting Properties & Methods

Child object can:

  • Use parent properties
  • Override methods
  • Extend behavior

13. Method Overriding

If child defines same method:

  • Child version is used
  • Parent still exists in prototype chain

14. Prototypal Inheritance Patterns

1. Delegation Pattern

Objects delegate behavior to prototype.


2. Combination Inheritance

Combines constructor + prototype methods.


3. Parasitic Inheritance

Adds extra features during inheritance.


15. Classes vs Prototypes

FeatureClassesPrototypes
SyntaxCleanVerbose
Under the hoodPrototypesPrototypes
InheritanceextendsPrototype chain

16. Object-Oriented Concepts Using Prototypes

  • Encapsulation → closures + private fields
  • Inheritance → prototype chain
  • Polymorphism → method overriding
  • Abstraction → exposed interfaces

17. Memory Optimization

  • Methods on prototype → single copy
  • Methods in constructor → multiple copies

Always prefer prototype methods for efficiency.

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥