1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Static Members In JavaScript

Discussion in 'JavaScript and AJAX' started by Sagar Jaybhay, Feb 18, 2020.

  1. Sagar Jaybhay

    Sagar Jaybhay New Member

    Joined:
    Jan 28, 2019
    Messages:
    26
    Likes Received:
    14
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    Static properties and methods are those that don’t change with 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 static member but we can make use of constructor function name to declare static fields or static methods in Javascript.

    The static variable is not created every time when an object is created.


    Code:
    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());
    
     
    shabbir likes this.

Share This Page