javascript - Understanding variable mistakes within closures? -
i learning closures. example given common mistake made when making closure:
function assigntorpedo(name, passengerarray) { var torpedoassignment; (var = 0; i<passengerarray.length; i++) { if (passengerarray[i] == name) { torpedoassignment = function() { alert("ahoy, " + name + "!\n" + "man post @ torpedo #" + (i+1) + "!"); }; } } return torpedoassignment; }
since loop completes before closure returned, value not match name. so, understand loop continues on before return happens.
my question comes this, example of correct way things:
function maketorpedoassigner(passengerarray) { return function (name) { (var = 0; i<passengerarray.length; i++) { if (passengerarray[i] == name) { alert("ahoy, " + name + "!\n" + "man post @ torpedo #" + (i+1) + "!"); } } }; }
i don't understand why in above example loop wouldn't continue past first time finds match, result in mismatched i. understand return stops function, don't understand connection between return , first match since don't happen (visually). understand how code knew stop if return within if function or loop.
i don't understand why in above example loop wouldn't continue past first time finds match
it would.
which result in mismatched i.
it wouldn’t, because checks if (passengerarray[i] == name)
every time. that’s wasteful, though; it’s unusual fix. better way pass index:
function maketorpedoassigner(passengerarray, i) { return function (name) { alert("ahoy, " + name + "!\n" + "man post @ torpedo #" + (i+1) + "!"); }; } function assigntorpedo(name, passengerarray) { (var = 0; i<passengerarray.length; i++) { if (passengerarray[i] == name) { return maketorpedoassigner(passengerarray, i); } } }
Comments
Post a Comment