0

I would like to know how can I create a module and manually create more instances of that module without impacting the global scope.

Right now I have something similar to this piece of code:

var myModule = (function(){
    ...
})();

myModule is at this point in the global scope of my app.

What can I do to encapsulate this somewhere and call a new instance of it anytime I need one?

I am looking for something similar with Require.js or Angular.

5
  • Have you looked at commonJS? Are you looking to do this client-side, server-side, or both? Commented Mar 4, 2015 at 21:57
  • I cannot add third party libraries in my project. Commented Mar 4, 2015 at 21:59
  • It isn't only for third party libraries. var coolModule = ["wow", "neat", "module"]; module.exports = coolModule; Then in another file: var coolModule = require("coolModule"); Is that what you have in mind? Commented Mar 4, 2015 at 22:01
  • Yes. But the result of require I want to be a new instance of coolModule Commented Mar 4, 2015 at 22:04
  • Got it. Why not make coolModule a javascript "class" and then call that constructor on module.exports? something like this Commented Mar 4, 2015 at 22:10

1 Answer 1

1
var myScope={};

(function(window) {

function Module(){
    console.log('new instance of Module');
};

Module.prototype.someFunction = function(){

};

window.myScope.Module = Module;

}(window));

myModule = new myScope.Module();

Something like this?

Sign up to request clarification or add additional context in comments.

1 Comment

The code is not working. Chrome says TypeError: Cannot set property 'Module' of undefined

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.