我创建了这个示例代码来演示我想要做什么。 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();
答案 0 :(得分:2)
您需要使用 bind
或使用 arrow function
才能获得正确的 this
值。
绑定:-
memoFunc() {
this.boo.anotherFunction(this.myFunction.bind(this));
}
箭头函数:-
memoFunc() {
this.boo.anotherFunction(()=>this.myFunction());
}