javascript

Prototype based Object Oriented Programming


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.

 

Example:

// 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.

 

Explanation:

  • We define a constructor function Employee to create Employee objects. Inside the constructor, we initialize properties name and age.
  • We add a method greet to the prototype of Employee objects using Employee.prototype. This method can be shared among all instances of Employee.
  • We create a new Employee object `employee1` using the new keyword.
  • We call the greet method on employee1.
  • Prototype-based programming in JavaScript offers flexibility and dynamic behavior. We can add or modify methods and properties on the prototype object, and those changes will be reflected in all instances that inherit from it. This dynamic nature is one of the key features of JavaScript's OOP paradigm.