I saw a tutorial which used few javascript classes
class Products(){}
class UI(){}
class Storage(){}
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(){ }
}
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() { }
}
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(){ }
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)
Yep, you are right.
is equivalent to
and when we create new object
operator
new
do this things:prototype
(real prototype, not just property with name prototype) to property with name prototype of StorageStorage.prototype
. Equivalent isvar obj = Object.create(Storage.prototype);
Storage.call(obj)
obj
we can assignobj
tostor
. Equivalent isstor = obj
.So we have new object which have
someMethod
in prototype and haven't access tostaticMethod
.You can always check babel repl if you have some doubt)
Yes, the classes look prettier but are just the old .prototype method of static definition. Read on JS prototypal inheritance.