Javascript Static Class Methods Tutorial

In this Javascript tutorial we learn about static methods that belong to a class, instead of an instance of a class.

We cover the static keyword, how to define and invoke them as well as what happens when static methods have the same name.

What is a static class method

A static class method is a method that belongs to the class, not the instance of a class. That’s to say, we don’t need an object to call a static class method, we call them directly from the class itself.

How to define a static class method

To define a static class method, we write the keyword static in front of a method definition.

Syntax:
static method_name() {

  // body
}
Example:
<script>

  class Person {

    static walk() {
      document.write("Walking...");
    }
  }

</script>

How to call (invoke) a static class method

As we’ve mentioned before, a static method doesn’t need an object in order for us to use it, it can be called directly from the class.

Example:
<script>

  class Person {

    static walk() {
      document.write("Walking...");
    }
  }

  Person.walk();

</script>

In the example above, we call the method without creating an object. When we run the example, the text is printed to the page.

Static class methods with the same names

We may have as many static class methods as we need, even ones with similar names. However, if we do have static methods with similar names, the translator will always invoke the last one.

Example:
<script>

  class Person {

    static walk() {
      document.write("Walking first...");
    }

    static walk() {
      document.write("Walking last...");
    }
  }

  Person.walk();

</script>

In the example above, the translator will run the second walk() method.

Summary: Points to remember

  • A static class method belongs to a class, not an instance.
  • We call a static method directly from the class, using the class name. We don’t need to create an object instance.
  • A static method uses the static keyword instead of the function keyword when we define it.
  • If more than one static method share the same name, the translator will invoke the last one.