Reputation: 9830
I'm trying to call a function without re-initializing (hope I used the correct word here) it every time I call it. So the first time it gets called, it should initialize, but after its initialized, it should just use that reference.
Here's the code I'm trying to do it with.
console.clear();
function mainFunction(e) {
var index = 0;
function subFunction() {
console.log(index++);
}
return subFunction();
}
window.addEventListener('click', mainFunction)
index
should increase by one every time mainFunction
gets called. The obvious solution, is to make index
a global variable (or just out of mainFunction
). But I need index to stay in
mainFunction`.
How can I make index
increment every time (using the same reference) mainFunction
gets called?
I tried assigning mainFunction
to a variable, then calling the variable in the event listener,
var test = mainFunction;
window.addEventListener('click', test)
but that didn't work. The results were the same.
Upvotes: 0
Views: 678
Reputation: 19113
Using OOP concept is the proper way to achieve this. The following should help you. If you want to do it in ES6 way follow this babel example
var mainFunction = function(val) {
this.index = val //initialize this with the fn parameter or set a atatic value
}
mainFunction.prototype.subFunction = function() {
return this.index++
}
var instance = new mainFunction(0)
window.addEventListener('click', function() {
console.log(instance.subFunction())
})
<p>Click to see the result </p>
Upvotes: 0
Reputation: 102194
If you don't want to make index
global (or one scope higher regarding mainFunction
), you can use a closure:
var mainFunction = (function () {
var index = 0;
return function () {return console.log(index++);}
})();
<button onclick="mainFunction()">Click</button>
Upvotes: 0
Reputation: 134
maybe try closures?
var main = (function () {
var index = 0;
return function () {return index += 1;}
})();
main()
main()
//index should be 2...
explain- The variable main is assigned the return value of a self-invoking function.
The self-invoking function only runs once. index initialize only once.
Upvotes: 0
Reputation: 26161
You should correct the code as follows;
console.clear();
function mainFunction(e) {
var index = 0;
function subFunction() {
console.log(index++);
}
return subFunction; // <<< don't invoke subfunction
}
window.addEventListener('click', mainFunction()) // <<< invoke mainfunction
Upvotes: 3