javascript closure - how come I refer to an undeclared variable -
this question has answer here:
- javascript closures vs. anonymous functions 11 answers
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
Post a Comment