Javascript-Static methods
The static keyword defines a static method that belongs to the class instead of an instance of that class. So, an instance is not required to return the static method. These methods are called directly on the class itself.
Syntax:
static methodName() { ... }
static propertyName [= value];
- The static keyword is provided to declare a static method.
- The static method can be of any name.
- A class can define more than one static method.
- In javascript, more than one static method with a similar name and JavaScript always invokes the last one.
- The static method can be define to create utility functions.
- You can use this keyword to return a static method within another static method.
Example :
<!DOCTYPE html>
<html>
<body>
<script>
class Test
{
static display()
{
return "static method is invoked"
}
}
document.writeln(Test.display());
</script>
</body>
</html>
OUTPUT:
static method is invoked
Example:
invoke more than one static method.
<!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:
static method is invoked static method is invoked again
Example:
More than one static method with similar names.
<!DOCTYPE html>
<html>
<body>
<script>
class Test
{
static display()
{
return "static method is invoked"
}
static display()
{
return "static method is invoked again"
}
}
document.writeln(Test.display());
</script>
</body>
</html>
OUTPUT:
static method is invoked again
Example:
static method within the constructor.
<!DOCTYPE html>
<html>
<body>
<script>
class Test {
constructor() {
document.writeln(Test.display()+"<br>");
document.writeln(this.constructor.display());
}
static display() {
return "static method is invoked"
}
}
var t=new Test();
</script>
</body>
</html>
OUTPUT:
static method is invoked static method is invoked
Example:
static method within the non-static method.
<!DOCTYPE html>
<html>
<body>
<script>
class Test {
static display() {
return "static method is invoked"
}
show() {
document.writeln(Test.display()+"<br>");
}
}
var t=new Test();
t.show();
</script>
</body>
</html>
OUTPUT:
static method is invoked