/
...
/
/
🏢
Prototype Inheritance
Search
Try Notion
🏢🏢
Prototype Inheritance
⚠️
Prototype Inheritance is no longer have any reason to use as ES6 provides a better way to inheritance the objects using classes!
Every object in JavaScript has a built-in property which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
Understand using example :
Lets create a prototype object!
const proto = { slogan: function () { return `This company is the best`; }, changeName: function (newName) { this.name = newName } }
JavaScript
Now lets store this prototype inside a variable
let harry = Object.create(proto);
JavaScript
Lets create 2 constructors namely employee and programmer to inherit them
// Employee constructor function Employee(name, salary, experience) { this.name = name; this.salary = salary; this.experience = experience; } // Programmer constructor function Programmer(name, salary, experience, language) { Employee.call(this, name, salary, experience); this.language = language; }
JavaScript
Now create objects from the constructors
// Slogan Employee.prototype.slogan = function () { return `This company is the best. Regards, ${this.name}`; } // Employee obj let harryObj = new Employee("Harry", 345099, 87); console.log(harryObj.slogan()) //The above object calls the prototype named slogan!
JavaScript
Lets inherit the prototype
// Inherit the prototype Programmer.prototype = Object.create(Employee.prototype); // Manually set the constructor Programmer.prototype.constructor = Programmer; let rohan = new Programmer("Rohan", 2, 0, "Javascript"); console.log(rohan);
JavaScript
Summary
from the above code we can understand that firstly we created a prototype and then we stored it inside a variable called harry, then we created 2 constructors namely employee and programmer. on a basic note we know that a programmer is an employee also so we can use the variables and logic which is stored in employee for programmer also and this is known as inheritance and inheriting the prototype object is known as Prototype Inheritance!
For reference :