Static methods in Class in JavaScript
static keyword is used to define a static method in a class. static method does not require an object of the class type to get called. We can just use the class name to call the static method.
Example
In the following, we define a class Student
with a static method named greeting()
.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
static greeting() {
console.log('Hello!');
}
}
Student.greeting();
Note that we not created a new object of type Student to call the static method.
Invisible to objects
static methods are invisible to objects. We cannot call a static method from an object. JavaScript raises TypeError
.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
static greeting() {
console.log('Hello!');
}
}
let student1 = new Student('Ram', 12);
student1.greeting();
Pass object to static method
We can pass objects to the static method.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
static greeting(student) {
console.log('Hello ' + student.name + '!');
}
}
let student1 = new Student('Ram', 12);
Student.greeting(student1);