What is static property and method in JavaScript?
The static properties and methods are assigned to the class function instead of to the prototype of the class function. So, we cannot call the static method and properties using the instance of the class. However, we can access the property and method directly using the class name.
The static properties and methods of a class are created using the static keyword.
class Male{static gender = "Male"; //static propertyconstructor(name, age) {this.name = name;this.age = age;}static printUser(male){ // static methodconsole.log(`Name - ${male.name } \nAge - ${male.age} \nGender - ${Male.gender}`);}}let user = new Male("Ram", 20);console.log("Accessing Male.gender static property");console.log(Male.gender);console.log("Calling static method Male.printUser");Male.printUser(user);console.log(user.gender); // undefined because static property not available in instanceconsole.log(user.printUser); // undefined because static method not available in instance
In the code above, we have:
-
Created a
Maleclass and addedgenderas a static property andprintUseras a static method. -
Created a new
Maleobject —user. -
Accessed the
genderstatic property usingMale.gender. -
Called the
printUserstatic method by class name likeMale.printUser(user).
We cannot access the static properties and static methods of a class with a user object. This is because static property and methods are assigned to the class.
The this value inside the static method is the class itself.
class Male {
static test() {
console.log(this === Male);
}
}
Male.test(); // true
To call a static method or access a static property within another static method of the same class, we can use the this keyword. (We cannot access other class static properties & methods using this; we
need to use the class name.)
class Male {
static gender = "Male";
static print2() {
console.log(this.gender);
}
static print(){
this.print2();
}
normalPrint(){
console.log(this.gender); // undefined
}
}
Male.print(); // Male
let user = new Male();
user.normalPrint(); //undefined
In the code above:
-
We have created a
Maleclass with two static methods (print,print2), 1 static property (gender), and 1 normal method (normalPrint). -
We have used
thisinside the static methodprintto call another static methodprint2of the same class. -
When we try to access the static property using
thisinside the non-static method (normalPrint), we getundefinedbecause the static methods and static properties are not accessible by class instance.