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.

Basic 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