JavaScript Static Tutorial

In this section, we will learn what the Static is and how it works in JavaScript.

Note: we’re assuming you’re already familiar with the JavaScript class as well as methods in classes.

What is Static in JavaScript?

There will be times when you want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member (property or method) that can be used by itself, without reference to a specific instance.

To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed via the name of that class without referencing to any object.

Also inside static members, `this` refers to the class itself. All other conventions are identical to prototype members.

To invoke a static member (property or method) of a class, we use the name of that class.

JavaScript Static Method

As mentioned before, a static method is a method in a class that proceeds with the keyword static.

Such a method is accessible only via the name of the class itself.

JavaScript Static Method Syntax:

static methodName(){

//body…

}

Example: using static method in JavaScript

class Person{
  constructor (firstName, lastName){
    this.firstName = firstName; 
    this.lastName = lastName;
  }
  static className(){
    return this;
  }
}
console.log(Person.className());

Output:

class Person{
        constructor (firstName, lastName){
          this.firstName = firstName; 
          this.lastName = lastName;
        }
        static className(){
          return this;
        }

In this example, the static member of the `Person` class is:

static className(){
          return this;
}

As the output shows, the `this` keyword in a static method refers to the class itself.

JavaScript Static Variable (Property)

Just like the static methods, a static property in a class is a property that proceeds with the keyword static.

Such property is only accessible with the name of the class itself.

Static Property Syntax:

static propertyName;

Example: using static variable in JavaScript

class Person{
  constructor (){
    this.firstName = "John"; 
    this.lastName = "Doe";
  }
  static number = 0;
  static sayHello(){
    return "Hello";
  }
}
console.log(Person.sayHello());
console.log(Person.number++);
console.log(Person.number++);
console.log(Person.number++);
console.log(Person.number++);

Output:

Hello

0

1

2

3
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies