javascript

Prototypes


Prototypes are fundamental to the language's object-oriented nature and inheritance model. Every JavaScript object has a prototype, which serves as a template for creating new objects. Understanding prototypes is crucial for grasping how inheritance and object relationships work in JavaScript.

In simple words, functions are first-class objects, which means they can have properties and methods just like any other object. When you define a function in JavaScript, it automatically gets a prototype property.

This prototype property is an object that acts as a blueprint for all instances created using that function as a constructor. Any properties or methods added to this prototype object become accessible to all instances created from that constructor function.

 

Example:


// Constructor function
function Employee(name) {
    this.name = name;
}

// Adding a method to the prototype
Employee.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name);
};

// Creating instances
var employee1 = new Employee("Rohit");
var employee2 = new Employee("Wasif");

// Both instances can access the method defined in the prototype
employee1.sayHello(); // Outputs: "Hello, my name is Rohit"
employee2.sayHello(); // Outputs: "Hello, my name is Wasif"