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

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

最佳答案

您需要使用 bind 或使用 arrow function 来获取正确的 this 值。

绑定(bind):-

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

箭头函数:-

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

关于javascript - 从另一个类调用函数时属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66267174/

相关文章:

javascript - Angular - 按模型值过滤 ng-repeat

node.js - 如何使用reactjs将导入的csv数据显示到表格中?

node.js - 在 Node/Express 中,如何使用 csv-to-array 来匹配或比较嵌套 Promise 中的值

node.js - 我使用nvm安装了最新的node.js版本,但是当我尝试更新npm时,它不起作用

javascript - 我所有的 Observables 错误 'takeUntil is not a function'

javascript - JQuery - 向下滚动时隐藏,向上滚动时部分显示,在顶部时完全显示

javascript - 根据单击的按钮以模态形式设置隐藏输入

javascript - CSS max-height 不起作用,但同一 div 的高度起作用

angular - 创建 'once emitting' 可观察对象

html - 如何使用 html 中的异步管道获取可观察值的嵌套值