我想避免在循环中评估条件,所以我考虑创建一个函数,返回变量中分配的正确处理,然后在循环中使用该变量。
基本上这个想法看起来像:
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。 但是,通过显示的代码,您应该更改一些内容。
-
就像你说的,
this
关键字存在问题。executeTreatment
和selectTreatment
中对ref
的所有引用都应以this
为前缀。 -
通过设置
ref = Treatment1()
,您可以将其设置为Treatment1
的结果,而不是对Treatment1
的引用。 然后你尝试在executeTreatment
中调用ref
,这只有在TreatmentX
返回一个函数时才有效。 因此,您可能希望将selectTreatment
作业更改为类似this.ref = this.Treatment1;