You need to call Init
to run any code inside of it. Now, that code inside is just regular JavaScript code, but an interesting one. Let's see why.
How
Your inner function is a so-called IIFE. What you can do to make it easier to read the outer function (Init
), is to replace the inner function with the result of the IIFE call.
Here are a few examples:
var x = undefined; // x === undefined
x = (undefined); // again
x = 3; // x === 3
x = (3); // again the same
x = 'some string'; // some string
x = ('some string'); // the same
So it's ok to put ()
around an object, you get the same object. The same for a function
x = function() {}; // x is that function now.
x = (function() {}); // the same.
But if you say x = 3;
, can you call x?
x = 3;
x(); // syntax error
x = (3);
x(); // again error. can't call a number.
But, if your x is a function, you can call it:
x = function() { console.log('Hi'); }; // you can call x now.
x(); // logs 'Hi'!
So if you do the same with parenthesis, it's the same:
x = (function() { console.log('Hi'); }); // again, the same.
x(); // no error, function called again!
So you can skip the assignment part:
// instead of x = (...); and the x(), you replace the x part right away.
(function() { console.log('Hi'); })()
// function body up to here ^^ now the call part.
Note that it won't work without the first pair of parens:
function() { console.log('Hi'); }(); // syntax error.
So you're putting the outer parens ()
just to cast that function expression into an object in-place.
Why
So that's how it works. But why? Because you wanna make sure nobody else calls your function! If you do this:
var x = function() {};
x();
Now there are at least two things that can happen that you might not want:
There might be a name clash. You might not know if there's an "x" already defined on wherever the outer function is gonna be called at, e.g. you bind
Init to some object which has x at scope or something.
Somebody can "steal" your x and call it again. Not necessarily steal, you just leak it (a subtle bug) and some other code calls x, expecting to find its own x, but in fact, it's your x now because it is reachable. And you wanted it not to be.
So you handily lock it away in anonymous function that's executed right away.
Hope this clears things a bit.