Question

I want to set up some code using the revealing module pattern. I'd like to set up the sub module to be able to access the private funcitons of the main module but im stuck on how to do this.

Here is some sample code ive been playing with:

var Module = (function() {

    function B(){
        console.log("B");

    };

    return {
        //B: B
    };

})();

var Module = Module || {};

Module.Utils = (function() {

    function C() {

        B();
    };

    return {
        C: C
    }

}).apply(Module);

Module.Utils.C();

How can i make it so that i can call a private function from the Utils module?

EDIT:

Jsut to clarify i want to be able to create a submodule that is added to the main module so if it helps the sub module could be Module as well. I was reading this: http://www.sitepoint.com/modular-design-patterns-in-javascript/ which uses apply() to add the second module but has to use the extend and privatise funcitons to add the module to the main one. I'd like to keep away from that if possible?

Another EDIT In short i want to have one main module and the second module to be in a new file that is only used on one section. i need the second module to still be able to reference the main module private functions. Is this possible?

Here is the code i mention:

//protected utility functions
    utils =
    {
        //add properties to an object
        extend : function(root, props)
        {
            for(var key in props)
            {
                if(props.hasOwnProperty(key))
                {
                    root[key] = props[key];
                }
            }
            return root;
        },

        //copy an object property then delete the original 
        privatise : function(root, prop)
        {
            var data = root[prop];
            try         { delete root[prop]; } 
            catch(ex)   { root[prop] = null; }
            return data;
        }
    };
Was it helpful?

Solution

Unless you are defining the submodule in the same lexical scope as the parent module, and doing some kind of closure over the "parent" private functions, you can't. You made the functions private, and so you need to be able to see them to call them. And you can't see them when defining a sub-module in a different place from the parent module. The only way you will get your desired structure is like this:

var Module = (function () {
    function B() {
        console.log("B");
    };

    var Utils = (function () {
        function C() {
            B();
        };

        return {
            C: C
        }
    })()

    return {
        Utils: Utils
    };
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top