Skip to content

44 Prototype Inheritance

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

The prototypical inheritance defines how objects inherit properties and methods from other objects.

  • In JavaScript, almost everything is an object
  • objects can inherit properties and behaviors from other objects through their prototypes.

1. Without Inheritance

Let's say we have phone functions.

  • Here we will notice getModelNumber is repeated
function Nokia() {
  this.modelNumber = "";
  this.getModelNumber = function () {
    return this.modelNumber;
  };
}

function Samsung() {
  this.modelNumber = "XX-XX-XXX";
  this.getModelNumber = function () {
    return this.modelNumber;
  };
  this.latestFeature = function () {
    console.log("Quad Camera");
  };
}


const samsungGalaxy = new Samsung();
console.log(samsungGalaxy.getModelNumber());

2. With Inheritance

  • The samsung proto type object has inherited the phone properties/methods Samsung.prototype = new Phone()
  • When we create any instance of the Samsung function we can access the inherited methods.
function Phone() {
  this.modelNumber = "";
  this.getModelNumber = function () {
    return this.modelNumber;
  };
}

function Samsung() {
  this.modelNumber = "XX-XX-XXX";
  this.latestFeature = function () {
    console.log("Quad Camera");
  };
}

Samsung.prototype = new Phone();

const samsungGalaxy = new Samsung();
console.log(samsungGalaxy.getModelNumber());

Clone this wiki locally