JavaScript Prototype

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 when a new object is created with constructor function, it has its own copy of constructor function with all properties and methods. It is not a good idea to have multiple copies of same function which are doing same thing. It will causes memory issues.

Prototype overcome this problem. When a function is created, a prototype property is added to it by JavaScript engine. Prototype property has constructor property by-default. With prototype approach 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 instance.
__proto__ It is used to get prototype object of a function to which it links to. 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 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 return false.
propertyIsEnumerable() It returns true if the specified property is enumerable otherwise return false.
toLocaleString() It returns string in local format.
toString() It returns string format of the object.
valueOf It returns the primitive value of the object.

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

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




<!DOCTYPE html>
function Student(firstName,lastName)
	return this.firstName+" "+this.lastName;
var student=new Student("Lalit","Mor");


Lalit Mor
Please Share