Search code examples
javascriptoop

Why would you build a static function in Javascript when you can build a regular function?


I am new to learning objects and classes in Javascript. I was just wondering, why would you attach a static method to a class, like so:

class MyClass {
  static myFunction(){
    console.log('foo');
  }
}

When you can just declare a regular, custom function outside of the class like one usually does?

function myFunction() {
  console.log('foo');
}

Solution

  • A static "method" is just a regular function that is attached to a class. This is useful when it belongs to that class semantically, and in extreme cases necessary in an inheritance hierarchy. The class name provides a visual namespace for accessing the function, e.g. Map.from does something different than Set.from.

    However, you would only ever do that when you already have an existing class. You would never create an empty class only to put a static method inside it. In such a case, a simple object literal with a regular object method suffices:

    const MyObject = {
      myFunction() {
        console.log('foo');
      },
    };
    MyObject.myFunction();