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 Male
class and added gender
as a static property and printUser
as a static method.
Created a new Male
object —user
.
Accessed the gender
static property using Male.gender
.
Called the printUser
static method by class name like Male.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 Male
class with two static methods (print
, print2
), 1 static property (gender
), and 1 normal method (normalPrint
).
We have used this
inside the static method print
to call another static method print2
of the same class.
When we try to access the static property using this
inside the non-static method (normalPrint
), we get undefined
because the static methods and static properties are not accessible by class instance.