javascript closure - how come I refer to an undeclared variable -


this question has answer here:

try head around javascript closures new me.
have tutorial indicates use:

function warningmaker( obstacle ){   function doalert (obs) {     alert("beware! there have been "+obs+" sightings in cove today!");   };   return doalert; } 

but confused "obs". parameter 'obstacle' automatically passed obs ?

a better example perhaps might be:

function warningmaker( obstacle ){   return function (number,location) {     alert("beware! there have been " +            obstacle +            " sightings in cove today!\n" +           number + " " + obstacle +           "(s) spotted @ " +           location + "!"          );   }; } 

either example you've got missing lines or isn't proper example closure. better example (with simplified code) be

function warningmaker(obstacle){    return function() {       alert("look!" + obstacle);    } } 

what above is, when function getting returned, reference obstacle in function body creates closure in memory , used whenever called ,

warningmaker("messi")(); // "look! messi" warningmaker("cr7")(); // "look! cr7" 

note in above, function returned being called. (i mean, empty parentheses)


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -