从另一个类调用函数时属性未定义

时间:2021-02-18 19:50:53

标签: javascript node.js typescript

我创建了这个示例代码来演示我想要做什么。 Run this code

无法读取未定义的属性“myValue”

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

1 个答案:

答案 0 :(得分:2)

您需要使用 bind 或使用 arrow function 才能获得正确的 this 值。

绑定:-

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

箭头函数:-

 memoFunc() {
        this.boo.anotherFunction(()=>this.myFunction());
    }
相关问题