On May 25, 2:35 am, blue <whiteli...@gmail.comwrote:
The following is fromhttp://developer.yahoo.com/yui/examples/dragdrop/dd-ontop.html
What does the (function(){ })(); syntax actually do? I'm going to guess
that is creates an unnamed function?! Many thanks.
<script type="text/javascript">
(function() {
var dd, dd2, dd3;
YAHOO.util.Event.onDOMReady(function() {
dd = new YAHOO.example.DDOnTop("dd-demo-1");
dd2 = new YAHOO.example.DDOnTop("dd-demo-2");
dd3 = new YAHOO.example.DDOnTop("dd-demo-3");
});
})();
</script>
A couple of years ago I was myself highly puzzled by this construct.
It is an age old task to define a function and to execute it
immediately. At older times - and this is what I used to - it was
simply
function myFunction() {
// statements
}
myFunction();
There are two drawbacks as I see it:
1st and the main one, I guess :-) - it is not cool
2nd is that myFunction unconditionally goes to the global space so
overrides any other myFunction defined before that. While the "rude
namespace" is not so important for a stay alone program, for a
libraries friendly program one may want to have "shy namespace" so no
global var will be created unless the needed identifier is not in
use; otherwise it warns or uses reserve identifiers.
In the latter case wrapped anonymous function may be of a good help:
(function() {
if (typeof myFunction == 'undefined') {
myFunction = functionBody;
}
else {
// namespace conflict handling
}
})();
It is important that the function has to be anonymous then because of
different treatment of function declaration wrapped into expression.
Having
(function f() {
// function body
})();
JavaScript doesn't create global function f but JScript does so global
f remains in the memory. One of rare situations when JavaScript vs.
JScript difference is important to know.