javascript - testing rewriting a simple loop with an immediate function -
i'm not sure why i'm getting error on following snippet (adapted javascript closure inside loops – simple practical example):
var funcs = {}; (var = 0; < 3; i++) { // let's create 3 functions funcs[i] = (function(n) { // , store them in funcs console.log("my value: " + n); // each should log value. })(i); } (var j = 0; j < 3; j++) { funcs[j](); // , let's run each 1 see }
it seems should run ok; know don't get.
here errror get:
thx help
you need return function, rather result of function. try:
funcs[i] = (function(n) { return function() { console.log("my value: " + n); } })(i);
example:
> var funcs = {}; (var = 0; < 3; i++) { funcs[i] = (function(n) { return function() {console.log("my value: " + n);} })(i); } (var j = 0; j < 3; j++) { funcs[j](); } value: 0 value: 1 value: 2
Comments
Post a Comment