0

I've seen this asked but I still don't understand the purpose of a static declaration of a method.

class Dog {
   constructor(breed) {
     this.breed = breed;
   }

}

The below is part I don't understand the true difference:

Dog.color = function () {
    return "black";
}

vs

Dog.prototype.color = function () {
    return "brown";
}

I understand that the protype function allows the method color to be called on whatever instance I created. Ex: var foo = new Dog() . foo.color();
But what is use case of a static method though if it can't be called on instances of the class?

Lionel Yang
  • 157
  • 1
  • 3
  • 1
    The only reason to use one would be to call it on objects that would themselves be classes. Like `[class {static color(){return "red";}, class {static color(){return "blue";}}]`. There are a few other legitimate uses. That said, most static members are just instances of bad code written by people who don't understand JavaScript and should be replaced by standalone functions. – Aluan Haddad Apr 05 '18 at 07:57
  • is it better practice to add the method inside the class definition or to make it a prototype method outside of the class definition? – Lionel Yang Apr 05 '18 at 08:06
  • @LionelYang inside if you can (ES2015+ or using a transpiler) – Aluan Haddad Apr 05 '18 at 08:08

0 Answers0