将回调函数分配给变量,并在高阶函数之外调用

Assign callback function to a variable and call outside of higher-order function

本文关键字:函数 高阶 调用 回调 分配 变量      更新时间:2023-09-26

我想给组件变量分配一个回调函数。。。例如

...
export class MyComponent {
       private myCompVar: any;
       myFunc = function(callback: (number) => void): void {
              this.myCompVar = callback;
       }
}

然后稍后从MyComponent中的另一个函数中调用此回调函数。例如:

...
export class MyComponent {
       private myCompVar: any;
       ...
       myOtherFunc(event): void {
               ...
               this.myCompVar(callbackParam);
       }
}

然而,当我像上面那样实现它时,当我试图在"myOtherFunc"内部调用"this.myCompVar"时,会出现一个错误,说它是未定义的。这让我很困惑,因为我已经确认回调在"myFunc"中被正确设置,并且它的类型是"function"在调用"myFunc"并返回后,myOtherFunc也将被调用,如预期的那样。

非常感谢您的帮助!

使用function会丢失正确的this上下文。我建议使用lambda(胖箭头函数),它正确地绑定到正确的this上下文:

myFunc = (callback: (number) => void): void => {
    this.myCompVar = callback;
}