Static Members and Prototype in JavaScript

Introduction

 
Static properties and methods are those that don’t change from one instance to another instance. Also, if we declared static function, then these functions can be used without creating an object of a class.
 
In Javascript, there is no special syntax to denote a static member, but we can make use of the constructor function name to declare static fields or static methods in Javascript.
 
The static variable is not created every time an object is created. 
  1. function Shape(){  
  2.   
  3.     //here count is variable and it is static declaration contains constructor function name  
  4.     Shape.Count=++Shape.Count||1;  
  5.   
  6.     // this is static function   
  7.     Shape.GetTotalCount=function(){  
  8.         return Shape.Count;  
  9.     }  
  10.   
  11.     // below is the instance variable  
  12.     this.val=0;  
  13. }  
  14.   
  15. var shape1=new Shape();  
  16. var shape2=new Shape();  
  17. var shape3=new Shape();  
  18.   
  19. alert(Shape.GetTotalCount());  

Prototype in Javascript

 
All Javascript objects inherit properties and methods from a prototype.
 
Javascript is a prototype-based language, When we create a function using JavaScript, the engine adds a prototype property inside a function and the prototype basically is an object. Also, it is called a prototype object.
 
A prototype is a special kind of enumerable object to which additional properties can attach to it and it will share across all the instances of that constructor function.
  1. function Employee(name)  
  2. {  
  3.   
  4.     this.FullName=name;  
  5. }  
  6.   
  7. var emp=new Employee("SAGAR JAYBHAY");  
  8. emp.greeting=function(){  
  9.     return "Hello, "+this.FullName;  
  10. }  
  11.   
  12.   
  13.   
  14. var emp2=new Employee("XYZ");  
  15. emp2.  
In the above code, emp2 is the object and for the greeting function, we created an emp object.
 
Since Javascript is a dynamic language, we are able to create a function but it is not accessible to the rest of the object. To overcome this kind of situation, we can use the prototype. 
  1. function Employee(name)  
  2. {  
  3.   
  4.     this.FullName=name;  
  5. }  
  6.   
  7. var emp=new Employee("SAGAR JAYBHAY");  
  8. // emp.greeting=function(){  
  9. //     return "Hello, "+this.FullName;  
  10. // }  
  11.   
  12. Employee.prototype.greeting=function(){  
  13.     return "Hello, "+this.FullName;  
  14. }  
  15.   
  16.   
  17. var emp2=new Employee("XYZ");  
  18. emp2.greeting();  
In the above code, we created a greeting function by using a prototype so it's accessible to all objects. The Prototype function allows you to override the function it's required. Thanks for reading!