Static Method-tutorial
In JavaScript, a static method is a method defined on the class itself rather than on its instances (objects).
This means you can call the static method directly using the class name without needing to create an object.
Static methods are often used for
Syntax:
This means you can call the static method directly using the class name without needing to create an object.
Static methods are often used for
- Utility functions
- Helper methods
- Operations that do not depend on instance data
Syntax:
class MyClass { static myStaticMethod() { // Code for static method }}
// Call the static methodMyClass.myStaticMethod();
You cannot call a static method using an instance of the class.
Example: Simple Static Method
<!DOCTYPE html><html>
<body>
<script> class Test { static display() { return "static method is invoked"; } }
document.writeln(Test.display()); </script>
</body>
</html>
Output
.webp)
Example: Multiple Static Methods
<!DOCTYPE html><html>
<body>
<script> class Test { static display1() { return "static method is invoked"; }
static display2() { return "static method is invoked again"; } }
document.writeln(Test.display1() + "<br>"); document.writeln(Test.display2()); </script>
</body>
</html>
Output
.webp)
Key Point
- Static methods are declared using the static keyword.
- They belong to the class itself, not to objects created from the class.
- Useful for helper and utility functions.
- Called directly using the class name, e.g., ClassName.methodName().