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:
    29
    Likes Received:
    17
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    https://sagarjaybhay.net
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice