Home >>Javascript Tutorial >JavaScript Prototype Object

JavaScript Prototype Object

JavaScript Prototype Object

JavaScript is a prototype-based language and each object contains a JavaScript prototype object that facilitates the objects to acquire properties and features from one another. Whenever a function is created the prototype property is added to that function automatically in JavaScript. This property is a JavaScript prototype object holding a constructor property.

Here is the syntax :

ClassName.prototype.methodName  

Need of a prototype

An object's corresponding functions are loaded into memory, whenever an object is created in JavaScript. Hence, a new copy of the function is created on each creation of an object. All the objects generally share the same function in a prototype-based approach. This states that there is no requirement of creating a new copy of function for each object. This leads to the loading up of functions into the memory only once.

Chaining of the Prototype

Each and every object constitutes a prototype object that acquires properties and methods from it in JavaScript. Please note that an object's prototype object may contain a prototype object and also acquires properties and methods, and the cycle goes on. This process is known as prototype chaining.

Example of JavaScript prototype object

1. Here is an example to add a new method to the 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("Sonu","Chowdhary");
var employee2=new Employee("Mithun", "Kumar");
document.writeln(employee1.fullName()+"<br>");
document.writeln(employee2.fullName());
</script>
Output :
Sonu Chowdhary
Mithun Kumar

2. Here is another example to add a new property to the constructor function:

<script>  
function Employee(firstName,lastName)  
{  
  this.firstName=firstName;  
  this.lastName=lastName;  
}  
  
Employee.prototype.company="Phptpoint"  
  
var employee1=new Employee("Rohit","Roy");  
var employee2=new Employee("Darwin", "William");  
document.writeln(employee1.firstName+" "+employee1.lastName+" "+employee1.company+"<br>");  
document.writeln(employee2.firstName+" "+employee2.lastName+" "+employee2.company);  
</script>  
Output : Rohit Roy Phptpoint
Darwin William Phptpoint

No Sidebar ads