JavaScript is a language based on prototypes that enables objects to inherit properties and characteristics from other objects. In this context, every object includes a prototype object.
In JavaScript, each time a function is defined, the prototype property is automatically assigned to that function. This property serves as a prototype object that contains a constructor property.
Syntax:
ClassName.prototype.methodName
What is the requirement of a prototype object?
Each time an object is instantiated in JavaScript, the associated functions are loaded into the memory. Consequently, a fresh instance of the function is generated with every new object creation.
In a prototype-based model, every object utilizes the same function. This eliminates the necessity to generate a distinct copy of the function for each individual object. Consequently, the functions are stored in memory a single time.
Prototype Chaining
In JavaScript, every object has an associated prototype object from which it inherits properties and methods. Furthermore, the prototype object of an object can also have its own prototype object, which similarly inherits properties and methods, and this process continues indefinitely. This concept is often referred to as prototype chaining.
JavaScript Prototype Object Example 1
Let’s explore an illustration demonstrating how to incorporate an additional method into a constructor function.
<script>
function Employee(firstName,lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
Employee.prototype.fullName=function()
{
return this.firstName+" "+this.lastName;
}
var employee1=new Employee("Martin","Roy");
var employee2=new Employee("Duke", "William");
document.writeln(employee1.fullName()+"<br>");
document.writeln(employee2.fullName());
</script>
Output:
Martin Roy
Duke William
Example 2
Let’s examine an illustration of how to introduce an additional property within the constructor function.
<script>
function Employee(firstName,lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
Employee.prototype.company="Example"
var employee1=new Employee("Martin","Roy");
var employee2=new Employee("Duke", "William");
document.writeln(employee1.firstName+" "+employee1.lastName+" "+employee1.company+"<br>");
document.writeln(employee2.firstName+" "+employee2.lastName+" "+employee2.company);
</script>
Output:
Martin Roy C# Tutorial
Duke William C# Tutorial