我创建了这个示例代码来演示我正在尝试做什么。 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/