-
Notifications
You must be signed in to change notification settings - Fork 0
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.
Let's say we have phone functions.
- Here we will notice
getModelNumberis 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());- 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());