Static methods in JavaScript is a way for providing class level methods. To declare a static method, we have to use static keyword as prefix with method name.
Syntax:
class className(){ static methodName(){ //method body } }
Ways to call static methods
1. Using Class name
ClassName.methodName();
2. On the constructor property of the class
this.constructor.methodName();
Points to remember:
- Static keyword is used as prefix with method name to declare a static method.
- We can call static method without instantiating the class.
- We can declare more than one static method in a class but if these have a similar name then JavaScript engine always invokes the last one.
- The static method are commonly used to create utility functions for an application.
- this keyword can be used to call a static method within another static method but we this keyword can not be used directly to call a static method within the non-static method. For these situations we either have to use the class name or as the property of the constructor like this.constructor.methodName().
Example:
<!DOCTYPE html> <html> <body> <script> class CollegeName { constructor() { this.college="NC College"; } } class Student extends CollegeName{ constructor(rollNo,name) { super(); this.rollNo=rollNo; this.name=name; } } var stu= new Student(1,"Sue"); document.writeln(stu.rollNo+" "+stu.name+" "+stu.college); </script> </body> </html>