why do we need static methods in class of javascript

Viewed 1855

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.

2 Answers

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.

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