3

I am trying to understand how create different instances of revealing module pattern. I have a code block below and create module1 and module2 instances of myRevealingModule and setting their name variables.But name of module1 is overwritten by module2. How can i have different name values for module1 and module2? What am i missing? Thanks!

var myRevealingModule = (function(){

    var name = 'Default';

    function setName (nameVal) {
       name = nameVal;
    };

    function getName () {
       return name;
    };

    return {
        fullName: name,
        set: setName,
        get: getName
    };

}());
var module1  = myRevealingModule;
module1.set("module1 name");
var module2  = myRevealingModule;
module2.set("module2 name");
4
  • 1
    All three variables, myRevealingModule, module1 and module2 hold references to the very same object. Looks like you are not looking for a module here, but rather a constructor, especially when you're talking about "instances". Modules are singleton objects. Commented Feb 29, 2016 at 23:13
  • Is it only way using a constructor to have 2 different modules by myRevealingModule? Could i create function callbacks for module1 and module2 to set name values? Thanks! Commented Feb 29, 2016 at 23:27
  • Yes, you need a constructor or factory that is capable of creating multiple objects (if you don't want to copy your code). Commented Feb 29, 2016 at 23:30
  • I think factory works for me. Thank you! Commented Mar 1, 2016 at 0:02

1 Answer 1

3

To make multiple instances, you have to remove the () at the end of the definition, so that you can call it separately each time you want to create a new instance. See the code comments in the block below for the three places a change was made:

var myRevealingModule = (function(){

    var name = 'Default';

    function setName (nameVal) {
       name = nameVal;
    };

    function getName () {
       return name;
    };

    return {
        fullName: name,
        set: setName,
        get: getName
    };

});    // removed the () here

var module1  = myRevealingModule();    // added () here to call factory function
module1.set("module1 name");
var module2  = myRevealingModule();    // added () here to call factory function
module2.set("module2 name");

This makes myRevealingModule() into a factory function. Each time you call it, it creates a new instance of your object.

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

Comments

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.