var - When will I need a javascript anonymous function immediately invoked? -



var - When will I need a javascript anonymous function immediately invoked? -

i see no situation need this

(function(param){ alert(param); //do })("derp");

istead of this

alert("derp"); //do

edit: ok, everybody, think got it. if have this:

var param = "x"; var heya = "y"; (function(param){ alert(param); //do })(heya);

the global variable "param" ignored in scope of anonymous function?

how scenario?

example #1 - uses invoked function look closes on single variable , returns function. resulting in beautiful, encapulated function.

var tick = (function () { //example of function look + closure var tock = 0; homecoming function() { homecoming ++tock; } }()); //it impossible alter `tock` other using tick() tick(); //1 tick(); //2 tick(); //3 tick(); //4

versus

example #2 - uses function declaration w/ global variable

//unnecssary global (unless wrapped in function, such jquery's ready function) var tock = 0; function tick() { homecoming ++tock; } tick(); //1 tock = 4; //tock exposed... , can manipulated tick(); //5 tock = 6; tick(); //7

it contrived illustration still real case scenario in situations people may want generate consecutive unique id's no possibility of collision.

javascript var

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -