2017-10-09 27 views
0

我想要避免評估循環中的條件,所以我想創建一個函數,返回變量中賦值的正確處理,然後使用該變量在循環動態地將一個函數分配給一個變量,然後在條件語句中使用它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) 
 
    } 
 

 

 
}

我不確定,但我認爲我對「這個」關鍵詞有問題!


我有資金這樣一個解決方案:

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); 
 
    } 
 

 

 
}

+0

不clear.You需要提供更多的'code'和細節。 – Sampath

+0

我是新的打字稿,項目是私人的!只要有耐心,告訴我什麼不清楚,並認爲你回覆 –

+0

如果你看到上面的'代碼'只有那麼你可以給別人解決方案嗎?你需要顯示所有相關的'代碼'。你在上面的代碼中使用'this'的地方? – Sampath

回答

0

這是很難確定您的問題正是因爲,像薩姆帕斯說,你不顯示怎麼樣這個類被使用。具體如何調用selectTreatement和executeTreatmeant。但是,通過顯示的代碼,您應該修改幾件事情。

  1. 就像你說的,this關鍵字存在問題。在executeTreatmentselectTreatment中的所有對ref的引用都應該以this作爲前綴。

  2. 通過設置ref = Treatment1(),你將其設置爲Treatment1的結果,而不是向Treatment1參考。然後您嘗試在executeTreatment中調用ref,如果TreatmentX返回一個函數,這將僅有效。所以,你可能想改變你的selectTreatment分配到像this.ref = this.Treatment1;

相關問題