Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8946277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T12:28:08+00:00 2026-06-15T12:28:08+00:00

I know I can create a self-invoking, nested function like this (function ns(){ (function

  • 0

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 js 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?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T12:28:09+00:00Added an answer on June 15, 2026 at 12:28 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know I can create a List<T> from IEnumerable<T> by doing myEnumerableCollection.ToList() , but
I would like to know how can I create a regexp to match the
I know that horizontal partitioning...you can create many tables. How can you do this
Suppose I have a class like this: class Alphabet(object): __init__(self): self.__dict = {'a': 1,
I know I can create a plot with line and dots using the type
Does anyone know how I can create a Completely transparent image or given am
I want to know if PHPExcel can: Create Excel spreadsheets with embeded image. The
I want to know if I can create a WebBrowser through code in Vb.NET,
I'm using python 3.1.1. I know that I can create byte objects using the
Does anyone know how I can Dynamically create an installation package that installs files

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.