0

I've tried to organize modules into NAMESPACES (see example below) and depend as little as possible on the latest cleverly-named JavaScript library or framework. I know this question isn't incredibly focused, but is this not a scalable approach? Are there alternative ways to scale my JavaScript that I should be aware of?

I should add that this is for a chrome app.

var MODULE_A = (function() {
  var A_CONSTANT_NUMBER = 1;
  var myPrivateVar_ = 2;

  var privateMethod1 = function() {
    console.log("A.privateMethod1");
  };

  var privateMethod2 = function() {
    console.log("A.privateMethod2");
  };

  return {
    aPublicVar1: 3,

    publicMethod1: function() {
      console.log("A.publicMethod1");
    },

    publicMethod2: function() {
      console.log("A.publicMethod2");
    }
  }
})();
2
  • 1
    I would suggest using an requirejs approach to this. Check out DI
    – FabianCook
    Dec 3, 2014 at 21:35
  • CommonJS (as used by Node.js and npm) + browserify: browserify.org . Also, ES6 will introduce modules. Dec 3, 2014 at 21:35

3 Answers 3

1

Have a look at requirejs. It makes what you suggest quite easy also adding dependency resolution/loading.

0

have you tried using http://browserify.org or any other dependency manager?

here is a very good discussion which could be very helpful to your problem. What is the purpose of Node.js module.exports and how do you use it?

0

Global namespacing does not give you enough of the benefits of what modern module system can give you.

You should look into either using commonjs if you are writing node aplications, or possible amd with requirejs if you are writing for a browser. Both give you the ability to properly define dependencies of one module on another, give you correct encapsulation and most importantly keep track of your dependency graph for you. Amd further gives you runtime asynchronous loading, which is nice but also comes with a few extra headaches.

Properly encapsulating your modules like this gives you a much better way to structure a large code base that can scale to infinity. Not that name spacing is not even an issue here, name are derived from file paths and/or module configuration. Locally you can name the return value or the module exports as you wish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.