我创建了此示例代码来演示我正在尝试做的事情。运行此代码。
无法读取未定义的属性“ 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
值。
绑定:-
memoFunc() {
this.boo.anotherFunction(this.myFunction.bind(this));
}
箭头功能:-
memoFunc() {
this.boo.anotherFunction(()=>this.myFunction());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句