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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -