JavaScript Prototype

The dictionary meaning of Prototype:
A first or preliminary version of a device or vehicle from which other forms are developed.

A prototype-based language is one that facilitates the objects to obtain properties and features from one another. In JavaScript, each object contains a prototype object, and the prototype property is added to each function automatically when created. It is thus known as prototype-based language.

Why prototype in JavaScript?
Every time a new object is created with a constructor function, it has its own copy of the constructor function with all properties and methods. It is not a good idea to have multiple copies of the same function which are doing the same thing. It will cause memory issues.

Prototype overcomes this problem. When a function is created, a prototype property is added to it by the JavaScript engine. Prototype property has constructor property by default. With the prototype approach, the constructor function will be loaded in memory once and every new object will share the same instance of the function.

Prototype object properties

Property Description
constructor It returns a function that created an instance.
__proto__ It is used to get a prototype object of a function to which it links. It is an invisible property of an object.

Prototype object methods

Method Description
hasOwnProperty() It returns true if an object contains the specified property as a direct property of that object and is not inherited through the prototype chain otherwise returns false.
isPrototypeOf() It returns true if the specified object is in the prototype chain of the object this method is called upon otherwise returns false.
propertyIsEnumerable() It returns true if the specified property is enumerable otherwise returns false.
toLocaleString() It returns a string in local format.
toString() It returns the string format of the object.
valueOf It returns the primitive value of the object.

Object’s prototype
As discussed earlier, the prototype is an object that is associated with every object in JavaScript. We can add additional properties to the prototype objects. In the case of the Object’s prototype properties will not be visible to other objects.

Function’s prototype
In the case of the Function’s prototype, additional properties will be visible to all other objects of the same constructor function.

Syntax:

Class_Name.prototype.method_Name

Example:

<!DOCTYPE html>
<html>
<body>
<script>
function Student(firstName,lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
Student.prototype.fullName=function()
{
return this.firstName+" "+this.lastName;
}
var student=new Student("Lalit","Mor");
document.writeln(student.fullName());
</script>
</body>
</html>