Understand Static Member and Prototype in JavaScript

Introduction

In this article we will Understand Static Members In JavaScript ,How to declare Static Variables and Prototype In JavaScript

Static Members in JavaScript

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.

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

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

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!

#javascript #javascript tips

Understand Static Member and Prototype in JavaScript
3.80 GEEK