I would not say its directly an alternative to ES6 classes since they need to be instantiated and can have its own context per instance. With this example, you will share the context with every call, similar to a static class. In fact, if you have the following example in TypeScript or ES6:
classclarkKent{privatestaticfullname='Clark Kent';privatestaticsecretIdentiy='Superman';staticintroduce(){return`Hi, my name is ${this.fullname}`;}staticissueReport(){return`${this.secretIdentiy} saves the day!`;}}
and you compile it to ES5, you will end up with almost the same code as the author described.
varclarkKent=/** @class */(function(){functionclarkKent(){}clarkKent.introduce=function(){return"Hi, my name is "+this.fullname;};clarkKent.issueReport=function(){returnthis.secretIdentiy+" saves the day!";};clarkKent.fullname='Clark Kent';clarkKent.secretIdentiy='Superman';returnclarkKent;}());
The benefit of using this module pattern over static classes is to get rid of the this keyword. From a user perspective, they behave pretty much the same though. One thing to take into account is that ES6 static classes' private properties can be accessed if you disable the TypeScript compiler. With the module pattern, it will get very hard (if not impossible) to access those.
Well, class is not static, it just has static methods on it, you can still do everything you do with any other class, plus you can run methods directly, which in combination gives a lot of flexibility.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I would not say its directly an alternative to ES6 classes since they need to be instantiated and can have its own context per instance. With this example, you will share the context with every call, similar to a static class. In fact, if you have the following example in TypeScript or ES6:
and you compile it to ES5, you will end up with almost the same code as the author described.
The benefit of using this module pattern over static classes is to get rid of the
this
keyword. From a user perspective, they behave pretty much the same though. One thing to take into account is that ES6 static classes' private properties can be accessed if you disable the TypeScript compiler. With the module pattern, it will get very hard (if not impossible) to access those.Im pretty sure es6 class doesnt have to be instantiated to do some of those things.
IE.
I think you are referring to:
I was not referring to static classes here :) I thought it would be clear with the rest of my comment.
Well, class is not static, it just has static methods on it, you can still do everything you do with any other class, plus you can run methods directly, which in combination gives a lot of flexibility.