I'm trying to pass the function assigned to "action" to "MainFunction" so I can reuse the structure of "MainFunction" while having variable actions that it can perform.
The problem is that the scope in which I am defining "action", does not have the definition of "counter" (resulting in "caught ReferenceError: counter is not defined"), but it will in the scope (of "Mainfunction") the function is actually run. (at "func();")
I know putting "counter" in a higher scope (like with the class variables or globally) would get around the issue, but I would rather not put variables in a higher scope than I'm using them.
Is it possible to reference "counter" while defining the function in the undermentioned context and if yes, how?
class tmp
{
#numbers = [];
get Numbers() { return this.#numbers; }
constructor()
{
this.#numbers.push(1);
this.#numbers.push(2);
this.#numbers.push(3);
this.#numbers.push(4);
this.#numbers.push(5);
let action = (function() { console.log(this.#numbers[counter]) }).bind(this);
this.MainFunction(action);
}
MainFunction(func)
{
let counter = 0;
for(let i = 0; i < this.#numbers.length; i++)
{
func();
counter++;
}
}
}
let num = new tmp();
Phil's comment would resolve my issue (Thank You!), but I would be referencing a "copy of counter" I'm passing to the function, not "counter" itself.