var c = (function(c) {
if (c === undefined) {
c = {};
}
function a() {
alert(1);
}
c.a = a;
return c;
}(c));
Let us take it step by step.
var c =
initializing a variable named c. Note that at this point, if a variable named as c is already initialized, c
would refer to that value only until we reach the end of this declaration.
( .... )
This means that whatever is inside should be treated as an expression.
function(c)
means that this "expression" is a function which takes an argument. This argument would henceforth be referred by the name c
until the function is over.
Any variable with the name c
which was declared outside the function scope would thus not be accessible directly here. Although if it is in the global scope, and the global scope happens to be the window object, it can referred to as window.c
.
if (c === undefined) { ... }
checks if the argument passed to it is undefined or not. Would return true if it is undefined, and thus execute what ever is inside the if block.
c = {}
set the variable c
to an empty object. So if the argument was (passed or) undefined, we define it ourselves here (and we define it to an empty object....).
function a() { alert(1); }
declared a function with the name a
calling which willl result in alerting the numeral 1. Note that this is just a function declaration. We haven't called the function yet.
c.a = a
The argument c
is now assigned a property named a
which refers to the function a
we just created.
return c
break out of the function with the return value as the final value of c
, after undergoing the changes we did to the argument passed.
(fun...}(c))
call the function that we just created, and pass to it as an argument the present value of c
. since we called the function as an expression, the result of this expression would be whatever is the return value of the function. And our function returns an object (which we passed to it), after assigning a property to it.
Since this expression was equated to the variable c
, the return value of the expression (which is the return value of the function), is now held with the variable c
.
If you read all this properly, you would know that the variable c
would now hold an object, which would have a property a
which is a function which alerts the number 1. And that object also retains the properties it might have had before.
If we de-uglify this code to make it readable just by making the variable names descriptive:
var myObject = (function(someObject) {
if (someObject === undefined) {
someObject = {};
}
function alertOne () {
alert(1);
}
someObject.alertOne = alertOne;
return someObject;
}(myObject));
This show is an episode from the series module revealing pattern, which tells us how to add additional properties to an object, which was declared previously, in an elegant manner without polluting the global scope.
Starring Immediately Invoked Function Expressions (IIFEs).