What kind of blocks do create closure in Javascript -
after working long javascript, i'm still having problems coming terms closure!
class="snippet-code-js lang-js prettyprint-override">(function() { var pages = ["one", "two", "three"]; (var index in pages) { var p = pages[index]; settimeout(function() { console.log(p); }, 500); } })();
shouldn't above snippet print one
, two
, three
? afaik p
within closure created for
block , should remain unchanged each of settimeout
s pick them up! why printing 3 three
s?
javascript has function scope, not block scope. so, when looping on array (p.s. don't utilize for..in
arrays), creating 3 closures. each closure create referencing same p
variable. when timeouts run, all print "three"
because printing same p
variable.
you need create new scope each element in array. lucky, javascript has built-in function this, .foreach
.
class="snippet-code-js lang-js prettyprint-override">(function() { var pages = ["one", "two", "three"]; pages.foreach(function(p){ settimeout(function() { console.log(p); }, 500); }); })();
when runs, runs callback each element. when callback ran, new scope created each element, works properly.
javascript closures
No comments:
Post a Comment