Chase Florell Chase Florell - 3 years ago 76
Javascript Question

How do I properly structure self-invoking nested functions within the larger picture of a namespaced application?

I know I can create a self-invoking, nested function like this

(function ns(){

(function Class(){

alert('ns.Class fired');

})();

})();​


But it's ugly, and doesn't look quite right.

My chops aren't what they should be, and I'm hoping someone can show me a better way to structure my namespaced app and still be able to utilize "some" self invoking functions.

// THIS DOESN'T WORK
// because I haven't called "ns"
function ns(){

(function Class(){

alert('fired');

})();

};​


For my purposes, the reason I'm asking this is to better namespace my JS in conjunction with jQuery.

So I'd like to be able to do something like this (which DOES WORK)

var ns = ns || {};
ns.Class = function(){};

ns.Class.Navigation = (function() {

$('#element').on('click', function() {alert('element clicked');});

})();​


But I'm not sure if this is the right way to structure larger (read: js heavy) apps?!?!


  • Is the weight of this too heavy?

  • Is there a smarter way to achieve this?


Answer Source

Well, First off: the fact that your calling the "main" IIFE ns suggests that you think of it as a namespace object, which isn't entirely correct. Namespaces are often created using IIFE's because they have the added benefit of closure scope(s). But in the end, namespaces are just a fancy word for Object (literals).
Take the most popular lib/toolkit/framework out there: jQuery. Basically, it's one huge IIFE, that constructs an equally vast object, that is assigned a number of methods and properties (well, references to function objects anyway). There are some other objects and variables created in that IIFE, but they are either not exposed to the global object at all, or (Very) indirectly.

Allow me to clarify:

var myNameSpace = (function()
{
    var invisibleVar = 'can\'t touch this';
    var objectLiteral = {sing: function()
        {
            return invisibleVar;//exposed, albeit indirectly
        },
        property: 'Hammertime'
    };
    var semiExposed;
    objectLiteral.getSemi = function(newVal)
    {
        return semiExposed;//change closure var
    };
    objectLiteral.changeSemi = function(newVal)
    {
        semiExposed = newVal;//change closure var
    };
    objectLiteral.restoreSemi = (function(initVal)
    {
        return function()
        {
            semiExposed = initVal;//restore to value set when main IIFE was executed
            //don't worry about what this references: use the force... of the scope
            return objectLiteral.getSemi();//<-- return init val
        };
    }(semiExposed));//pass initial value to this scope
    var notExposedAtAll = function()
    {//can't be called but inside the main IIFE scope (and subsequent scopes)
        objectLiteral.foo = 'But it adds a public property';
    };
    objectLiteral.changeMe = function()
    {
        notExposedAtAll();//called in default context (either null or global, but it doesn't matter here)
    };
    return objectLiteral;//direct exposure
}());

This uses some of the basic principals all toolkits/libs, and actually all decent JS scripts share: using functions as first class object, using them as expressions to create a temporary scope etc...)
IMO, it makes a good case for IIFE's: the scope gives you plenty of time to assign any object to a variable, so regardless of How you create a method (with or without an IIFE), you don't have to worry about what this references at any given time, just use the variables.
You can implement some basic data hiding, too. In this example the initial value of semiExposed is being passed to an IIFE, and preserved within its scope. Nothing can muck this up (well, that's not quite true at the moment), so you can allways revert to the initial values of any property.

However, I will admit, IIFE's can make your code harder to read as it grows, and I completely understand why you'd not want to use them too much. You could look into bind, it'll help you cut back on many IIFE's, but there is a down-side. Some ppl still use IE8, for example, which doesn't support bind.
But an other option would be: create a simple IIFE factory function:

function giveScope(varsFromScope,toFunction)
{
    return function()
    {
        var passArguments = Array.prototype.slice.apply(arguments,[0]);//get args from call
        passArguments.push({scope:varsFromScope});
        toFunction.apply(this,passArguments);
    };
}
var pseudoClosure = giveScope({scopeContext: this, something:'else'},function(arg1,arg2)
    {
        //function body here
        arguments[arguments.length - 1].currentContext;//<== "closure scope"
        this;//called context
    });

That way, you can get rid of some IIFE's, by replacing them with a simple function call to which you pass an object. Easy, and X-browser compatible.

Lastly, your first snippet is something that I do tend to use in event delegation:

var target = e.target || e.srcElement;
var parentDiv = (function(targetRef)
{
    while(targetRef.tagName.toLowerCase() !== 'div')
    {
        targetRef = targetRef.parentNode;
    }
    return targetRef;
}(target));

That way, I don't have to create another veriable in the same scope, my targetRef is assigned to parentDiv when the div is found, and targetRef is GC'ed, I'm finished with it, so there's no need for that variable to stay in scope.

It's getting rather late now, and I don't know if I'm making much sense at all. Bottom line is: You might hate IIFE's, but you can't really do without them.
If it's the mass of parentheses that bother you, you might be glad to know that you don't have to use them. Any operator that forces the JS engine to interpret the function declaration as an expression will do:

(function()
{
}());
//can be written as:
!function()
{
}();
//or
~function()
{
}();
//or when assigning the return value, you don't even need anything at all:
var foo = function()
{
    return 'bar';
}();
console.log(foo);//logs bar

Perhaps you prefer an alternative notations? But honestly: you may not like the syntax, but I'm afraid you're going to have to live with it, or switch to coffeescript or something.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download