2

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:

  1. Using prototype

    var myModule = function() {
      this.myProperty = 1;
    }
    myModule.prototype.myMethod = function() {
      //...
    }
    //...
    
  2. Using an object:

    var myModule = {
      myProperty: 1,
      myMethod: function() {
        //...
      }
      //...
    }
    
  3. Using a immediately/self invoked function:

    var myModule = (function() {
      var myProperty = 1; 
      this.myMethod = function() {
        //...
      }
      //...
      return this;
    })();
    
  4. Using a regular function (and initializing with new):

    var myModule = function() {
      this.myProperty = 1; 
      this.myMethod = function() {
        //...
      }
      //...
    };
    
  5. 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.

  • As a side note: I initially had this question on codereview, but was told that this site could be more appropriate. I see how the question may be a bit broad, so any feedback to improve it is welcomed. – Alvaro Montoro Aug 26 '18 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.