0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
NNNeeded
  • 1
  • 1
  • 1
    Yes, pass it in as a parameter... `const action = (counter) => { console.log(this.#numbers[counter]) }` – Phil Apr 19 '23 at 00:30
  • 1
    *'but it will in the context the function is actually run'* this is not how scope works. – pilchard Apr 19 '23 at 00:32
  • @pilchard My statement isn't incorrect. (though it might be unclear) If I were to replace "func();" with the value of "action" it runs no problem. I know (the basics of) how scope works, I just can't figure out how to link to the correct scope from where I'm defining the function in the constructor. – NNNeeded Apr 20 '23 at 16:09

0 Answers0