Forum Moderators: open
I was wondering if someone might be able to explain the following JavaScript to me.
<html>
<head>
<script type="text/javascript">
(function load(){
alert("load");
})();
function onload(){
alert("onload");
}
</script>
</head>
<body onload="onload()"></body>
</html>
The part I do not fully understand is (function load(){do stuff...})();
How does javascript interprerate the brackets ()(); containing the function? Is this javascript attempt at overloading (i know you cant overload with javascript, but just curious to what its doing)? as it is called before the page onload.
TIA,
-Gs
[edited by: Alternative_Future at 11:42 am (utc) on Feb. 12, 2008]
(function load(){
alert("load");
})();
The '{' operator is subject to a syntactic ambiguity in JavaScript: it can begin a block or an object literal. We wrap the text in parens to eliminate the ambiguity.
function foo() { /* ... */ }
// Call foo:
foo(); // Note the parens
Well, foo could instead be a self-instantiating function by moving the parens:
function foo() { /* ... */ }();
(function foo() { /* ... */ })();
[edited by: Fotiman at 5:24 pm (utc) on Feb. 12, 2008]
(function(){var a; ...;})()
This form of code has some advantages. You can haves part of your code and variables totaly hidden from the other javascript code.
In my example, 'a' is a local variable not accessible outside of "function(){}"
You can define sub-function in this function, and use them directly in the code inside function(){}, or in an event set inside this function.
(function(){
var a;function testSomething(v) {
do something with v;
}function handleClick() {
some code;
}a=testSomething(document.getElementBy...);
document.body.addEventListener('onclick',handleClick,false);
})()
The top onload is inside an anonymous function, in other words, and cannot be seen by body onload.