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 class name to access this property and method directly.

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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.