JavaScript_Succinctly
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Self-invoking anonymous function statements<br />
It’s possible to create an anonymous function statement that is self-invoked. This is<br />
called a self-invoking anonymous function. In the following sample, we create several<br />
anonymous functions that are immediately invoked.<br />
Sample: sample93.html<br />
<br />
// Most commonly used/seen in the wild.<br />
(function (msg) {<br />
console.log(msg);<br />
})('Hi');<br />
// Slightly different, but achieving the same thing:<br />
(function (msg) {<br />
console.log(msg)<br />
} ('Hi'));<br />
// The shortest possible solution.<br />
!function sayHi(msg) { console.log(msg); } ('Hi');<br />
// FYI, this does NOT work!<br />
// function sayHi() {console.log('hi');}();<br />
<br />
Notes<br />
According to the ECMAScript standard, the parentheses around the function (or<br />
anything that transforms the function into an expression) are required if the function is to<br />
be invoked immediately.<br />
Functions can be nested<br />
Functions can be nested inside of other functions indefinitely. In the following code<br />
sample, we encapsulate the goo function inside of the bar function, which is inside of<br />
the foo function.<br />
Sample: sample94.html<br />
<br />
var foo = function () {<br />
100