If I have:
function firstFunction(){
var counter = 0;
secondFunction();
secondFunction();
secondFunction();
secondFunction();
}
function secondFunction(){
counter++;
}
I get an error because of the local scope of the variable, but how else am I to do something like this without using global variables?
One way is to use a closure:
(function() {
var counter = 0;
function firstFunction() {
secondFunction();
secondFunction();
secondFunction();
secondFunction();
}
function secondFunction() {
counter++;
}
})();
Alternately, you could pass in the value of counter to secondFunction, like this:
function firstFunction() {
var counter = 0;
counter = secondFunction(counter);
counter = secondFunction(counter);
counter = secondFunction(counter);
counter = secondFunction(counter);
}
function secondFunction(counter) {
return ++counter;
}
Use Object to pass counter by reference
function firstFunction() {
var myObj = new Object();
myObj.counter = 0;
secondFunction(myObj);
secondFunction(myObj);
secondFunction(myObj);
secondFunction(myObj);
}
function secondFunction(obj) {
obj.counter++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With