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.

0

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Please consider that this is a duplicate question.
It's a duplicate question, but this is the clearest answer.
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();

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.