I am building APIs for an application. I want to know if there is any difference between writing the functionality methods as this:
class Foo {
static method1(req, res) {}
static method2(req, res) {}
}
and
class Foo {
method1(req, res) {}
method2(req, res) {}
}
I know static methods are made directly on the class and are not callable on instances of the class and they are often used to create utility functions but I just want to know if there is a disadvantage or any effect if static is not added while creating the functionalities for the application.
If static
is not added, then the method can only be called on an instance of the object.
If static
is added, then the method can only be called with the class name prefix, not an instance of the object.
If you have a method that could be static (does not reference any instance data or use this
to refer to an object instance), then you can make it either static or not static. If you make it non-static, it will still work just fine, but it will only be callable on an instance of the object itself or with a direct reference to Foo.prototype.method()
.
So, the disadvantage of not making a static method actually be declared static is that it's not as clean to use it when you don't have an instance of the object around. That's what static methods were invented for - to make it clean to declare and use functions namespaced to your class that don't require an instance.