How to extend the namespace when using the "Immediately invoked function expression" in Javascript?

StackOverflow https://stackoverflow.com/questions/16690072

  •  30-05-2022
  •  | 
  •  

Question

Ive been using this way of defining a namespace

(function( skillet, $, undefined ) {
//Private Property
var isHot = true;

//Public Property
skillet.ingredient = "Bacon Strips";

//Public Method
skillet.fry = function() {
    var oliveOil;

    addItem( "\t\n Butter \n\t" );
    addItem( oliveOil );
    console.log( "Frying " + skillet.ingredient );
};

//Private Method
function addItem( item ) {
    if ( item !== undefined ) {
        console.log( "Adding " + $.trim(item) );
    }
}    
}( window.skillet = window.skillet || {}, jQuery ));

Now Id like to extend skillet to a sub namespace, like skillet.module and let module behave in the same way as skillet - protect its undefined, and allow private and public members.

Ive tried the other way of defining a namespace, inside skillet, do skillet.theObject = { blah: function() {} }; and so on but that only gives me a normal object and not private and public members in it.

Was it helpful?

Solution

Simply add another immediately invoked function expression within the function, and pass an assignment argument to it so that it's initialised.

(function (skillet, $, undefined) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function () {
        var oliveOil;

        addItem("\t\n Butter \n\t");
        addItem(oliveOil);
        console.log("Frying " + skillet.ingredient);
    };

    (function (module) {
        module.test = function () { // access this by typing skillet.module1.test()
            if (isHot !== undefined) console.log(pour('water') + (isHot ? ', cold!' : ', hot!'));
        }

        function pour(what) {
            return 'Pouring ' + what;
        }
    )(skillet.module1 || (skillet.module1 = {})); // no need for undefined and $ rewriting as already done in parent function


    //Private Method
    function addItem(item) {
        if (item !== undefined) console.log("Adding " + $.trim(item));
    }    
}(window.skillet || (window.skillet = {}), jQuery));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top