根据条件将函数动态分配给变量,然后在循环打字稿 2.3.4 中使用它



我想避免在循环中评估条件,所以我考虑创建一个函数,返回变量中分配的正确处理,然后在循环中使用该变量。

基本上这个想法看起来像:


export class myClass{
ref;
Treatment1(){code}
Treatment2(){code}
Treatment3(){code}
selectTreatment(){
   if(condition1){
      ref = Treatment1()
   else if(condition2){
      ref = Treatment2()
   else (condition3){
      ref = Treatment3()
}
   executeTreatment(){
      setInterval(ref(),300)
   }

}

我不确定,但我认为我对this关键字有问题!


我找到了这样的解决方案:

export class myClass{
ref:any;
Treatment1(){code}
Treatment2(){code}
Treatment3(){code}
selectTreatment():Function{
   if(condition1){
      return ()=>{Treatment1()};
   else if(condition2){
      return ()=>{Treatment1()};
   else (condition3){
      return ()=>{Treatment1()};
}
   executeTreatment(){
      this.ref=this.selectTreatement();
      setInterval(ref(),300);
   }

}

很难确切地确定你的问题是什么,因为就像Sampath所说的那样,你没有展示如何使用这个类。 具体来说,如何调用 selectTreatement 和 executeTreatmean。 但是,通过显示的代码,您应该更改一些内容。

  1. 就像你说的,this关键字存在问题。 executeTreatmentselectTreatment中对ref的所有引用都应以 this 为前缀。

  2. 通过设置 ref = Treatment1() ,您可以将其设置为Treatment1的结果,而不是对Treatment1的引用。 然后你尝试在executeTreatment中调用ref,这只有在TreatmentX返回一个函数时才有效。 因此,您可能希望将selectTreatment作业更改为类似 this.ref = this.Treatment1;

最新更新