Revealing Module Pattern with a constructor

Kyle Gobel picture Kyle Gobel · Aug 22, 2013 · Viewed 10k times · Source

I'm having a bit of trouble figuring out the best way to implement this.

I want a module that has a constructor that takes in an argument that stores it for later use within the module.

var ModuleB = function(moduleA) {
    this.moduleA = moduleA;
}

ModuleB.prototype = function() {
    //private stuff/functions
    function someMethod() {
        moduleA.doSomething();
    }

    //public api
    return {
        someMethod : someMethod
    };
}();

In some other file

//ModuleA defined elsewhere
var moduleA = new ModuleA();

//...

var module = new ModuleB(moduleA);
module.someMethod();

Now above in someMethod, moduleA is undefined, and this, is the global window object. Can someone explain how I would get access to moduleA? I don't understand what happens to this.moduleA = moduleA; after the constructor. I'm not really a javascript developer so if I'm using the wrong pattern here or something, feel free to chime in.

Answer

jbabey picture jbabey · Aug 22, 2013

You are very close, but you're missing something important in your definition of someMethod.

EDIT: is is easier to tell what works and what doesn't if you change the name of the module property in ModuleB:

var ModuleA = function() {}

ModuleA.prototype = (function () {
    return {
        someMethod: function () {
            return 'foo';
        }
    };
}());

var ModuleB = function(moduleA) {
    this.innerModule = moduleA;
}

ModuleB.prototype = (function () {
    return {
        doStuff: function () {
            return this.innerModule.someMethod();
        }
    };
}());

var moduleA = new ModuleA();

var moduleB = new ModuleB(moduleA);
console.log(moduleB.doStuff()); // prints "foo"

http://jsfiddle.net/mN8ae/1/