Functions have names, but anonymous functions do not; MooTools uses them everywhere.
Note
Anonymous functions are one-time use like disposable lighters. In MooTools, we use them to one-time define a method; reusable disposable functions!
To define and call an anonymous function raw JavaScript wraps a function in parentheses:
(function(){document.title=location.href;alert('done');})();
Nothing is returned, and the function is not assigned to a function identifier; when the () function syntax is appended, the function self-executes.
MooTools' use differs slightly in that we will pass this anonymous function as an argument to a MooTool object and bind it to an identifier; the anonymous syntax does not change.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:50px; text-align:center;">Click Me</div> <script type="text/javascript"> // (A) would change title, alerts done in true lisp style //(function(){document.title=location.href;alert('done');})(); // (B) saves the anonymous function in a variable var af = (function(){ document.title=location.href; alert('done'); }); // (C) "calls" the anonymous function (commented out) //af(); // (D) returns the function (and alerts its text) //alert($lambda(af)); // note, lambda is deprecated // (E) binds function to the click event on my_trigger $('my_trigger').addEvent('click', af ); </script>
A indicates a classical JavaScript style, anonymous, self-executing function.
B (used in our recipe) assigns a self-executing function to an identifier.
C in raw JavaScript would call the self-executing function.
D demonstrates deprecated usage of MooTools' $lambda object.
E (used in our recipe) passes the function to be bound to click events.
Speaking in a strictly semantic world where anonymity is not compromised by that golden oldie 1984 and Orson Wells' cameras and dictatorial fiction, an anonymous function cannot be called more than once; it is defined, executed, and lost. Assigning it to an identifier would, in a pure discourse, render it no longer anonymous. Verily, the point of a recipe on anonymous functions is but to aid us in our understanding behind the science on how functions are passed to objects and then later executed as methods. Read up on more about what anonymous functions are on your favorite wiki site and send the author assertively argumentative proof as to the gamut of viewpoints regarding this subject.