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? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -