IIFE, more examples

I want expand my last post (Immediately invoked function expression aka IIFE), by more examples of using IIFE.

IIFE can be also used like this:

var foo = function() {
// code
}();

However, it’s better practice to do this like this, because of code readability:

var foo = (function() {
// long code
})();

If you have on your page jQuery and maybe other JS library that uses $ sing to access it. You may use this little pattern to pass library to IIFE, the way it will not makeĀ conflicts. And also get advantage of $ access to that library:

(function($) {
// code using $
})(jQuery);

Also it helps with rendering animations:

(function animation_loop() {
    window.requestAnimationFrame(animation_loop)
    render():
})();

It’s protect against unwanted globals:

(function() {
     window.public = 'foo';
     var private = 'bar';
})();

// latter on

public; // foo
private; // undefined

Useful if you want compute and return value in one statement:

var browser = {
    vendor_prefix : (function() {
        var prefix;
        // compute stuff
        return prefix;
    })()
};

Create a class in one statement:

var MyClass = (function() {
    function MyClass(foo) {
        this.foo = foo;
    }

    MyClass.prototype = {
        bar : 'baz'
    };

    return MyClass;
})();

Creating private variables:

var number = (function() {

    var num =0,
    add = function(n) { num = num + n;},
    get = function() { return num; };

    return { add:add, get:get};
})();

create private functions:

var foo = (function() {
    var priv = function() { alert('Hi'); },
        publ = function() { priv(); }

    return publ;
})();

Sources: