Prototype-based programming is a style of object-oriented programming (OOP) in which inheritance is achieved using prototype objects. In JavaScript, objects are linked to a prototype object from which they inherit properties and methods. This is different from class-based OOP, which is found in languages like Java or C++.
In JavaScript, each object has an internal property called [[Prototype]] (often referred to as the "dunder" or "double underscore" prototype). This [[Prototype]] links to another object called its prototype. When you access a property or method of an object, JavaScript looks for that property or method first in the object itself. If it doesn't find it, it looks in the object's prototype, and then in the prototype's prototype, and so on, until it either finds the property or reaches the end of the prototype chain.
// Constructor function for creating Employee objects
function employee(name, age) {
this.name = name;
this.age = age;
}
// Adding a method to the prototype of Employee objects
employee.prototype.greet = function() {
return "Hello, my name is " + this.name + ".";
};
// Creating a new Employee object
let employee1 = new Employee("Wasif", 23);
// Calling the greet method
console.log(employee1.greet());
// Output: Hello, my name is Wasif.