static method
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);