javascript - Variable scope and sharing information without global variables -
if have:
function firstfunction(){ var counter = 0; secondfunction(); secondfunction(); secondfunction(); secondfunction(); } function secondfunction(){ counter++; }
i error because of local scope of variable, how else without using global variables?
one way use closure:
(function() { var counter = 0; function firstfunction() { secondfunction(); secondfunction(); secondfunction(); secondfunction(); } function secondfunction() { counter++; } })();
alternately, pass in value of counter
secondfunction
, this:
function firstfunction() { var counter = 0; counter = secondfunction(counter); counter = secondfunction(counter); counter = secondfunction(counter); counter = secondfunction(counter); } function secondfunction(counter) { return ++counter; }
Comments
Post a Comment