Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we need static methods in class of javascript [duplicate]

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.

like image 442
Vansh Bhardwaj Avatar asked Jul 22 '26 03:07

Vansh Bhardwaj


1 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.

like image 100
Robert Harvey Avatar answered Jul 24 '26 15:07

Robert Harvey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!