...

View Full Version : What is the use of this construct: (function() { some code })(); ?



simonvdm
07-26-2011, 06:02 PM
Hi there,

I'm trying to better understand the Google Analytics asynchronous tracking code and am wondering why it uses the following construct: (function() { some code })();

How is that different from some code?

Thank you for your answers.
(FYI: although I am familiar with dynamic programming languages, I'm new to Javascript.)

Regards,
Simon

DaveyErwin
07-26-2011, 06:21 PM
Hi there,

I'm trying to better understand the Google Analytics asynchronous tracking code and am wondering why it uses the following construct: (function() { some code })();

How is that different from some code?

Thank you for your answers.
(FYI: although I am familiar with dynamic programming languages, I'm new to Javascript.)

Regards,
Simon

So basically its an anonymous function that calls itself ...

(function(){alert("I called myself")})()

Now that doen't seem very useful because

alert("I called myself")

does the same thing .

Its usefullness usually is the fact
that a "closure" is made in the function.
Please google "closure".

siberia-man
07-26-2011, 07:28 PM
This construction is used in several cases.

First of all -- an anonymous function is created and called immediately. Very useful when you need do something and keep the global scope off of some interim variables.

Second one -- is closure. But this is not obvious case to demonstrate closures.

Third -- obfuscating. Passing some global variables to this function is good practice to decrease size of the resulting file after obfuscating process.


How is that different from some code?
So, the answer for your question is the first description.

DaveyErwin
07-26-2011, 09:37 PM
Another use for...
(function() { some code })();
might be to return a function ...
(function() { return someFunction})();

maybe like this...




<html>
<body>

<script type="text/javascript">
addEvent = (function(){
if (window.addEventListener){
return function(obj, evType, fn){
obj.addEventListener(evType, fn, false);
return true;
}}
else if (window.attachEvent){
return function(obj, evType, fn){
var r = obj.attachEvent("on"+evType, fn);
return r;
}}
}
)();

alert(addEvent)

</script>
</body>
</html>


in firefox and ie9 this will alert
function(obj, evType, fn){
obj.addEventListener(evType, fn, false);
return true;
}
but in ie<9 it will alert
function(obj, evType, fn){
var r = obj.attachEvent("on"+evType, fn);
return r;
}

siberia-man
07-26-2011, 10:10 PM
Agree with you, DaveyErwin.

You have shown an example of an environment-dependent implementation. Depending on the actual environment (mostly browsers) the definite function will be assigned and executed.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum