Practicing some of the ES7 features, I started developing a class to perform some actions on the DOM and use the new features. I used Babel to make it work on the browser, and the code looks something like this:
class myModule {
constructor() {
this.myProperty = 1;
}
myMethod = () => {
//...
}
//...
}
Now I wanted to make it work as a small plugin/module/library in vanilla JS. Started looking on this site and online, and saw that the architecture of the different plugins/modules that I found looks like one of these:
Using
prototype
var myModule = function() { this.myProperty = 1; } myModule.prototype.myMethod = function() { //... } //...
Using an object:
var myModule = { myProperty: 1, myMethod: function() { //... } //... }
Using a immediately/self invoked function:
var myModule = (function() { var myProperty = 1; this.myMethod = function() { //... } //... return this; })();
Using a regular function (and initializing with
new
):var myModule = function() { this.myProperty = 1; this.myMethod = function() { //... } //... };
Using a function that returns an object (seems like a combination of 2 and 4, there are some variants):
var myModule = function() { var myProperty = 1; function myMethod() { //... } return { myProperty: myProperty, myMethod: myMethod } };
The compiled code with Babel looks like the 4th on this list, and I left it like that; but, is it better to use one of the other methods (or a different way all together)? And by "better" I mean a best practice or standard way of designing them.