Static Members and Prototype in JavaScript

Static properties and methods in JavaScript

Static properties and methods are those that don't change from one instance to another instance. Also, if we declare a static function, 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 use 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. 

function Shape(){  
  
    //here count is variable and it is static declaration contains constructor function name  
    Shape.Count=++Shape.Count||1;  
  
    // this is static function   
    Shape.GetTotalCount=function(){  
        return Shape.Count;  
    }  
  
    // below is the instance variable  
    this.val=0;  
}  
  
var shape1=new Shape();  
var shape2=new Shape();  
var shape3=new Shape();  
  
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 a prototype 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 it, and it will share across all the instances of that constructor function.

function Employee(name)  
{  
  
    this.FullName=name;  
}  
  
var emp=new Employee("SAGAR JAYBHAY");  
emp.greeting=function(){  
    return "Hello, "+this.FullName;  
}  
  
  
  
var emp2=new Employee("XYZ");  
emp2.  

In the above code, emp2 is the object, and we created an emp object for the greeting function.

Since Javascript is a dynamic language, we can create a function that is not accessible to the rest of the object. To overcome this kind of situation, we can use the prototype. 

function Employee(name)  
{  
  
    this.FullName=name;  
}  
  
var emp=new Employee("SAGAR JAYBHAY");  
// emp.greeting=function(){  
//     return "Hello, "+this.FullName;  
// }  
  
Employee.prototype.greeting=function(){  
    return "Hello, "+this.FullName;  
}  
    
var emp2=new Employee("XYZ");  
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!