ctx2002 said:
HI all:
I often see people write code like as below to invoke code block:
(
function() { do some thing here}
) ()
my question is why do like this, and what is benefit.
regards
It can help keep the global namespace clean. It's defining an anonymouse
function and calling it immediately, and unless some kind of closure is
created, it will be discarded. All variables defined inside the function
are lost with it. For example, if you wanted to do this following code
INLINE:
var x=2;
var y=3;
var z=x*y;
alert(z);
You've multipled 2 by 3 and alerted 6. But behind you, you've left (and
possibly overwritten if they already existed) global variables x, y and
z. Where as this code below leaves/overwrites nothing:
(function(){var x=2;var y=3;var z=x*y;alert(z);})()
Same result, less pollution.
It can be just people showing off how many JS tricks they know though.