DEV Community

Ermal Shuli
Ermal Shuli

Posted on

Did JavaScript objects have static methods before ES6 class static methods?

I saw a tutorial which used few javascript classes

class Products(){}
class UI(){}
class Storage(){}
Enter fullscreen mode Exit fullscreen mode

I thought in the wild I'm not going to always be working with ES6 classes, so I should be able to recreate these with ES5 objects

function Car(price) {
    this.price = price,
    this.someMethod = function(){ }
}
Enter fullscreen mode Exit fullscreen mode

But the Storage class had only static methods which threw me of a bit

class Storage {
  static saveProducts(products) { }
  static getProduct(id) { }
  static saveCart(cart) {  }
  static getCart() { }
}
Enter fullscreen mode Exit fullscreen mode

I understand the difference, we can't directly access Car.someMethod() but we can access Storage.getCar().

My question is, is this a good practice? And most importantly is this the way to implement this functionality without using classes

function Storage(){
  this.someMethod(){ }
}
Storage.prototype.someOtherMethod = function(){ }
Storage.theStaticMethod = function(){ }
Enter fullscreen mode Exit fullscreen mode

Though I'm relatively new at JavaScript I have never seen static methods before ES6. I've always seen methods created through the prototype. Though it does pass by tests (the Storage.theStaticMethod works exactly as static theStaticMethod as far as I can tell) is my understanding correct? Why does it look wrong?

Top comments (2)

Collapse
 
stoope profile image
Stepan Kurennykh

Yep, you are right.

class Storage {
  static staticMethod() { }
  someMethod() { }
}
Enter fullscreen mode Exit fullscreen mode

is equivalent to

function Storage() {}
Storage.staticMethod = function staticMethod() {};
Storage.prototype.someMethod = function someMethod() {};
Enter fullscreen mode Exit fullscreen mode

and when we create new object

var stor = new Storage();
Enter fullscreen mode Exit fullscreen mode

operator new do this things:

  1. create new object and set this object prototype (real prototype, not just property with name prototype) to property with name prototype of Storage Storage.prototype. Equivalent is var obj = Object.create(Storage.prototype);
  2. call Storage() and bind created object as this inside function. Equivalent is Storage.call(obj)
  3. when function have executed and done some staff with obj we can assign obj to stor. Equivalent is stor = obj.

So we have new object which have someMethod in prototype and haven't access to staticMethod.

You can always check babel repl if you have some doubt)

Collapse
 
jdforsythe profile image
Jeremy Forsythe

Yes, the classes look prettier but are just the old .prototype method of static definition. Read on JS prototypal inheritance.