Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property undefined when calling a function from another class

I created this sample code to demonstrate what I'm trying to do. Run this code.

Cannot read property 'myValue' of undefined

class Foo {
    myValue = 'test123';
    boo: Boo;

    constructor(boo: Boo) {
        this.boo = boo;
    }

    memoFunc() {
        this.boo.anotherFunction(this.myFunction);
    }

    myFunction() {
        console.log(this.myValue);
    }
}

class Boo {
    anotherFunction(func: () => void) {
        func();
    }
}

const foo = new Foo(new Boo());
foo.memoFunc();
like image 449
Burak Avatar asked Nov 02 '25 07:11

Burak


1 Answers

You need to either use bind or use an arrow function to get the correct this value.

Bind :-

 memoFunc() {
        this.boo.anotherFunction(this.myFunction.bind(this));
    }

Arrow function :-

 memoFunc() {
        this.boo.anotherFunction(()=>this.myFunction());
    }
like image 146
Lakshya Thakur Avatar answered Nov 03 '25 22:11

Lakshya Thakur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!