In principle, a self-signed anonymous function (more technically referred to as an IIFE expression or a function call immediately called) matches the declaration of a named function, and then immediately calls it. The only difference from IIFE is that it does not have a name, so it can only be done locally (not called from another location) and therefore not added to the current namespace.
Thus, you can use it at any time when a bunch of code inside the function will be useful and when this code will ever need to be called in the current specific context.
In some places where it is usually:
In any kind of loop, which includes some local variables and some asynchronous operations (ajax, timeout, etc.), where you want to access these local variables separately for each iteration of the loop in the asynchronous completion function.
To encapsulate some top-level code that runs once with its own scope and its own local variables, which are private and separate from the global namespace.
To create unlimited scope for any reason.
Examples:
Loop index (freezes the loop index separately for each setTimeout() call):
for (var i = 0; i < max; i++) {
Encapsulating the top level of the code (creates a private but constant variable that is not in the global scope):
(function() { var cntr = 0; window.getUniqueId = function() { return ++cntr; }; })();
Create locally accessible shortcuts in your code that would otherwise be a top-level area.
function Dictionary(initialData) { // call parent constructor Set.apply(this, arguments); } (function() { // inherit from Set var proto = Dictionary.prototype = new Set(); var base = Set.prototype; // Set constructor back to us proto.constructor = Dictionary; // override of the base class .add() // add(key, value) // add(Dictionary) // add({key1: value1, key2: value2}) proto.add = function(arg1, arg2) { if (arg1 instanceof Set) { // call base class to just add another Set base.add.call(this, arg1); } else if (typeof arg1 === "object") { // cycle through the object and add all properties/values to the Set for (var prop in arg1) { if (arg1.hasOwnProperty(prop)) { this._add(prop, arg1[prop]); } } } else if (typeof arg2 !== "undefined") { // must be add(key, value) this._add(arg1, arg2); } return this; } proto.get = function(key) { return this.data[key]; } // See rest of code here: https://github.com/jfriend00/Javascript-Set/blob/master/dictionary.js })();
jfriend00 Apr 17 '14 at 3:33 2014-04-17 03:33
source share