Bur*_*rak 4 javascript node.js typescript
我创建了这个示例代码来演示我正在尝试做的事情。运行此代码。
无法读取未定义的属性“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();
Run Code Online (Sandbox Code Playgroud)
您需要使用bind或 使用 anarrow function来获取正确的this值。
绑定:-
memoFunc() {
this.boo.anotherFunction(this.myFunction.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
箭头功能:-
memoFunc() {
this.boo.anotherFunction(()=>this.myFunction());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
857 次 |
| 最近记录: |