user3991417
user3991417

Reputation:

Define multiple instances of Module (pattern) in JavaScript

I am trying to find best way how to create multiple instances and configure my module according Module pattern.

Currently I have

var Logger = (function () {
    // Private members
    var _settings = {
        json: JSON,
        output: console
    };
    // Private methods
    var _log = function (info) {
        _settings.output.log(info);
    };
    var _dump = function (info) {
        _log(_settings.json.stringify(info));
    };
    // Change default settings
    var changeSettings = function (settingsArgs) {
        if (settingsArgs !== undefined) {
            if (settingsArgs.json !== undefined) {
                _settings.json = settingsArgs.json;
            }
            if (settingsArgs.output !== undefined) {
                _settings.output = settingsArgs.output;
            }
        }
    };
    return {
        init: changeSettings,
        log: _log,
        dump: _dump
    };
})();

I have several questions about this pattern.

  1. What is the best way to provide configuration to the module, I simply created setter for private settings fields, but I feel this is not the best way it can be implemented. Please suggest right approach.

  2. How to create multiple instances of my module. As I understood, module commonly used to encapsulate global objects and logic (like singletons), so most of time only one instances of module exists, but I need to have multiple instances. In my case this can be useful for example, I can create one logger ConsoleLogger another one will be AlertLogger the difference is output, but now I can only have one instance.

Please suggest the right way to follow, I have already read a lot of articles but haven't found answers to my questions. Thanks

Upvotes: 5

Views: 4422

Answers (1)

andree
andree

Reputation: 3224

What you have there is Module used as an Immediately-Invoked-Function-Expressions (IIFE), because of () at the end. Therefor, you are creating instance at class definition time and you can only have a single instance. You could clone one instance and have multiple of them, but that is not a good thing to do.

If you want to have multiple instances, you should remove IIFE expression at the end. Also, you can pass settings as constructor param:

 var Logger = function (settingsArgs) {};

Now, you can create multiple instances:

 var consoleLogger = new Logger({output: console});
 var alertLogger = new Logger({output: alert}); // change this line probably, for this to work _settings.output.log(info);

Upvotes: 9

Related Questions