-
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());- While executing
samsungGalaxy.getModelNumber()javascript checks if the methos is available in the function - If it doesn't find, it goes one level up to the proto type of the Samsung function
- And it keeps going until it finds the method or null (the proto type of Ovject)