0
class Myclass{

    private _myvar = "foo"

    function1(){
        this.function2(this.function3)
    }

    function2(myfunction){
        myfunction()
    }

    function3(){
        this.function4()
    }

    function4(){
        consoleLog(this._myvar)
    }
}

var myClass = new Myclass()

Does anyone know why running the following lines of code for the above class creates an unknown type error?:

myClass.function1();
myClass.function2(myClass.function3);

But running the following does not?:

myClass.function3();
myClass.function4();

I'm hoping this can be solved by binding in some way but I'm not sure how.

  • 1
    Does this https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback or https://stackoverflow.com/questions/65656591/pass-class-method-as-function-argument-while-maintaining-this-context or https://stackoverflow.com/questions/71537568/passing-class-method-as-callback-to-another-class-in-javascript answer your question? – Alex Wayne Aug 26 '23 at 21:49
  • `this.function2(() => this.function3())` is probably the most idiomatic solution. – Alex Wayne Aug 26 '23 at 21:51
  • I tried ` this.function2( () => { this.function3() } )` and it worked. Is there another more declarative way of doing this that highlights what is going on under the hood? – Joseph Hutton Aug 27 '23 at 10:25
  • this also works `this.function2(this.function3.bind(this))` -- [Playground Link](https://www.typescriptlang.org/play?ssl=6&ssc=9&pln=6&pc=50#code/MYGwhgzhAECyCepIQN4Cg3S9ADgJwEsA3MAFwFNoB9AW3hL2gF5oAiAMwHtPWNtp2AVwB2wUgU7CAjAAoAlOn79SACwIQAdENHjJAJhmr1WkWInCAzBoBGBYQBNDaiHLmZsAXz7ZtZ-TLpfXWEALmh5ZgA+aCJOAnsFdyVoQNNg+SToL0yg8wt5RWToI01cyQAWDP5s-jLhSsSi6GBJCE4Qcg0QTgBzJ2NaejA8N2q0bIYU+ABhcChmaGFyAHc4RDmIDLQ6WeQTHXNZOSA) – Joseph Hutton Aug 27 '23 at 11:48

0 Answers0