1

I'm currently working on an app which uses the javascript module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html). Can javascript classes be used in combination with this pattern to create a structure like in C#, where classes are nested inside namespaces?

I've currently got this:

app.modules.foo = class {
    constructor() {
        // Module variables
    }

    // Module functions

    get init() {
        // Module initialization function
    }
}

Which I would then call like this:

var app = {
    modules: {},
    init: function () {
        "use strict";

         this.modules.foo.init();
    }
};

window.addEventListener("DOMContentLoaded", function() {
   app.init(); 
});
Gilbert
  • 11
  • 2
  • 1
    Sure you can. It works, right? – Bergi Nov 12 '17 at 21:33
  • It didn't work but I found out it was because I forgot to add the 'new' keyword. Now it looks like this: `app.modules.foo = new class { constructor() { // Module variables } // Module functions get init() { // Module initialization function } }` – Gilbert Nov 13 '17 at 00:03
  • Is there any reason to use this instead of `app.modules.foo = (function() {})();` ? I would expect the classes to be more useful because they are extendable but haven't seen anyone using this inside the module pattern. – Gilbert Nov 13 '17 at 00:09
  • Ah, right, I missed that you wanted a singleton object, not a constructor. You should only use classes if you want to create multiple instances. [Do not use `new class {…}`!](https://stackoverflow.com/a/38741262/1048572) – Bergi Nov 13 '17 at 15:40

1 Answers1

0

Sure! It looks like you are trying to have modules represent singleton objects, and not classes that can be instantiated? If this is the case, check out https://github.com/jojois74/recycle.js

Inside each module closure, you can create an object var obj = {}; Add properties; obj.foo = function() {/*etc*/}; Then return it: return obj.

Take a look at the readme.md for details.

jojois74
  • 795
  • 5
  • 10