Skip to content

JavaScript static property and method | Code

  • by

The JavaScript static properties and methods are assigned to the class function instead of to the prototype of the class function. You can’t call the static properties and method using the instance of the class. Use the class name to access this property and method directly.

Here’s how you can define and use static properties in JavaScript:

class MyClass {
  static staticProperty = 'I am a static property';

  static getStaticProperty() {
    return MyClass.staticProperty;
  }
}

console.log(MyClass.staticProperty); // Accessing the static property directly
console.log(MyClass.getStaticProperty()); // Accessing the static property using a static method

In the example above, staticProperty is a static property of the MyClass class. You can access it using the class name MyClass.staticProperty, or you can create a static method like getStaticProperty to access it, as shown in the example.

Static properties are commonly used for constants, configuration values, or for sharing data among all instances of a class without having to create an instance of the class. They are available in modern JavaScript, such as ES6 and later.

JavaScript static property

Simple example code can’t access the static properties and static methods because they are assigned to the class.

<!DOCTYPE html>
<html>
<body>
  <script>

   class Person{

    static school = "ABC XYZ"; 
    constructor(name, age) {
      this.name = name;
      this.age = age;
    }

    static printUser(male){ 
      console.log(`Name - ${male.name } \nAge - ${male.age} \nGender - ${Person.gender}`);
    }
  }

  let user = new Person("Ram", 20); 

  console.log(Person.school);
  Person.printUser(user);

  //static property not available in instance 

  console.log(user.gender);
  console.log(user.printUser);
</script>
</body>
</html> 

Output:

JavaScript static property and method

Use the this keyword to call a static method or access a static property within another static method of the same class.

<script>

   class Person {
    static school = "XYE";

    static print2() {
      console.log(this.school);

    }
    static print(){
     this.print2(); 
   }
   normalPrint(){
     console.log(this.school); // undefined 
   }
 }

  Person.print(); // XYE

  let user = new Person();
  user.normalPrint(); //undefined 
</script>

Do comment if you have any doubts or suggestions on this Js static topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading