What is the lifetime of variables inside a self calling function in javascript -
i've been trying understand following code:
var add = (function () { var counter = 0; return function () {return counter += 1;} })(); add(); add(); add();
here add
assigned return value of anonymous self calling function -- function function() { return counter += 1 }
. first time add()
called returns 1
expected. second time add()
called returns 2
.
my question since counter
defined inside function wouldn't every time function finishes execution counter
should die? is, after first call add()
1 displayed. out of function shouldn't counter
forget it's previous value , destroyed stack automatic
variables are?
what lifetime of variables inside self calling function in javascript
the same variables in other kind of javascript function: exist long can referenced, means long past time function contains them returns.
your counter
variable continues exist after iife returns because function creates , returns (return function () {return counter += 1;}
) closure on variable. variable exist long function exists.
more technically: calling function creates called execution context call, has variable enviroment object. function created during call receives reference outer variable environment object; object, objects, exists long there's reference it, , functions keep object alive. variables properties of variable environment object, , exist long references object they're on. (this simplified form.) while in theory entire variable environment object kept, in practice javascript engines free optimize if effects of optimization aren't observable, variable isn't used closure may (or may not) released, depending on engine , code in function.
your iife can called once, there can 1 counter
, it's common function creating closure called more once, in case have multiple variable objects, , multiple copies of variables closed over.
example:
function hellobuilder(name) { var counter = 0; return function() { ++counter; display("hi there, " + name + ", greeting #" + counter); }; } var hellofred = hellobuilder("fred"); var hellomaria = hellobuilder("maria"); hellofred(); // "hi there, fred, greeting #1" hellofred(); // "hi there, fred, greeting #2" hellomaria(); // "hi there, maria, greeting #1" hellomaria(); // "hi there, maria, greeting #2" hellofred(); // "hi there, fred, greeting #3" function display(msg) { var p = document.createelement('p'); p.appendchild(document.createtextnode(msg)); document.body.appendchild(p); }
in above, function returned hellobuilder
closes over both name
argument , counter
variable. (because arguments stored on execution context's variable object.) can see after calling twice, there 2 variable objects, each own name
, counter
, 1 referenced each function asked hellobuilder
create.
Comments
Post a Comment