Skip to content

45 Prototype Sharing

Biswajit Sundara edited this page Aug 20, 2023 · 5 revisions

We can share properties and methods among objects using prototype inheritance.

  • By adding properties and methods to an object's prototype,
  • those properties and methods become available to all instances of that object type.
  • This promotes code reusability and efficient memory usage
  • as the shared properties and methods are stored in memory only once, rather than for each instance.

1. The Problem

  • When we create instance of the function using constructor
  • it will have it's own copy of the properties/methods
  • This is a wastage of the memory.
//Constructor function
function User(name){
    this.name = name;
    this.getDetails = function(){
        console.log(this.name);
    }
}

// Instance of the functions
let user1 = new User('Mark');
let user2 = new User('Bis');

//Accessing the method
user1.getDetails();
user2.getDetails();

//Print the instances
console.log(user1);    //name, getDetails()
console.log(user2);    //name, getDetails()

2. The solution

If we bind the getDetails to user.prototype then it will be shared across instances

  • We will observe when we print instances user1, user2 it only prints the name. the getDetails is not attached to it
function User(name){
    this.name = name;
}

User.prototype.getDetails = function(){
    console.log(this.name);
}

let user1 = new User('Mark');
let user2 = new User('Bis');

user1.getDetails();
user2.getDetails();

console.log(user1);  //{name: 'Mark}
console.log(user2);  //{name: 'Bis'}
  • user1.__proto__ & user2.__proto__ will have getDetails & constuctor function
  • user1.__proto__ === user2.__proto__ returns true
  • Basically User.prototype has the getDetails method and the user1 & user2 proto types inherit the method.

3. Another Example

  • We are sharing the sayHello method among all instances of the Person constructor without duplicating it for each instance.
  • The sayHello method is stored in the prototype and is accessible to all Person objects.
  • Prototype inheritance allows you to modify shared methods or add new ones dynamically.
  • Any changes made to the prototype are reflected in all instances created from the constructor.
//Define constructor function
function Person(name, age) {
  this.name = name;
  this.age = age;
}

//Add shared method to proto type
Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

//create instances
const person1 = new Person("Alice", 30);
const person2 = new Person("Bob", 25);

//Access shared methods
person1.sayHello(); 
person2.sayHello(); 

Summary

  • Modern JavaScript introduced the class syntax and the extends keyword,
  • which provide a more structured and familiar way to work with inheritance.
  • However, under the hood, class in JavaScript is still based on prototype inheritance.

Clone this wiki locally