javascript function closure working -
i going through javascript book , have encountered following code on closure
function constfunc() { var funcs = []; (var = 0; < 10; i++) { funcs[i] = function () { return i; } } return funcs; } var f = constfunc(); f[5](); the output not 5. explanation given "nested functions not make private copies of scope". grateful if explain above statement.
when call constfunc loop runs , assigns function each element of funcs array. functions each return value of i, changes on each iteration of loop 0 9.
that means once constfunc has finished executing i have value of 9. when call 1 of functions in array returns value of i we've seen 9. value of i not captured on each iteration of loop.
you can force captured via closure in loop:
for (var = 0; < 10; i++) { (function (i) { funcs[i] = function () { return i; }; }(i)); } in case creating new variable same value i on every iteration of loop. can see in action here.
by passing i function end copying value of it. on first iteration i has value 0. pass value new function (the argument i different variable i declared in loop initialiser) , return value array function. way, each array function returning different i, instead of each returning same i.
Comments
Post a Comment