CodesJava

Easy learning with example program codes

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

PropertyDescription
constructorIt 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

MethodDescription
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.
valueOfIt 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.

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>

Output:

Lalit Mor
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status