简体   繁体   中英

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();

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());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM