Site icon i2tutorials

Javascript-Static methods

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];

 

 

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

 

 

Exit mobile version