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

Viewed 48

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');
}
2 Answers

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();

Mostly for namespacing. Imagine you need 10 functions of related feature. Instead of taking up 10 names from global scope, using static methods you use just one global name, being the class name.

Remember that apps often end up being complex, using 3rd party libraries. Name clashes is a real problem when complexity comes to play.

Related