7

why do we need static methods in class of javascript.

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  static hello(x) {
    return "Hello " + x.carname;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = Car.hello(mycar);

I know that , Static methods are called directly on the class (Car from the example above) - without creating an instance/object (mycar) of the class. But what's the use of/point of static method in classes JS.

Vansh Bhardwaj
  • 427
  • 5
  • 9

2 Answers2

11

To be able to call the method without creating an instance of the class.

There's some benefit to this. To call an instance method, you would have to create a new instance of the class, and then call the method (it's a two-step process). With static methods, this isn't necessary.

More info here:

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

Static functions are typically referentially-transparent functions. A referentially-transparent function is one that doesn't rely on instance state for its proper functioning. Such a function is easy to reason about, because you don't have to consider anything that is happening outside of the function to understand what it does.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 1
    A specific example of creating objects that is impossible to achieve with the constructor alone since `async constructor` is illegal, is to define static asynchronous factory functions, which delegate to the constructor after awaiting asynchronously provided dependencies that are parameters of the constructor. – Patrick Roberts Oct 22 '20 at 17:46
  • Please consider that this is a duplicate question. – trincot Oct 22 '20 at 17:48
  • It's a duplicate question, but this is the clearest answer. – Andrew Jul 26 '22 at 12:21
0

Static methods give the method to the constructor of the class... not the instance. This makes it so you can call ClassName.functionName(param); Instances will still have this function, but it makes it so you can call the function on the class instead of the instance. For example, this doesn't work:

class jump
  doJump() {
    console.log(7);
  }
}
jump.doJump(); // Error
var jumper = new jump();
jumper.jump() // => 7

But this does:

class move {
  static doMove() {
    console.log("works");
  }
}
move.doMove();
var t = new Move()
t.doMove();
cs641311
  • 80
  • 2
  • 12
  • 2
    these examples don't really demonstrate the utility of static class methods, since both of these could just as easily be achieved with the easier-to-understand object literals `const jump = { doJump() { ... } };` and `const move = { doMove() { ... } };` respectively. Also, `t.doMove();` would not work. – Patrick Roberts Oct 22 '20 at 17:48