2017-04-25 169 views
1

我有兩個功能在我的角度項目,一個是aceitaProposta做這個:減少JavaScript代碼

aceitaProposta() { 
    this.aceita(); 
    // some other code 
} 

,我有recusaProposta

recusaProposta() { 
    this.recusa(); 
    // some other code 
} 

現在,this.recusathis.aceita之間的唯一區別是第一個遞增一個屬性,第二個遞減它。我想知道是否有一種方法可以將這兩個函數轉換爲一個函數,僅使用if之類的函數來識別其遞減或遞增。這樣,我會在aceitaPropostarecusaProposta中調用相同的函數。例如:

aceitaProposta() { 
    this.incrementDecrement(); 
    // some other code 
} 

recusaProposta() { 
    this.incrementDecrement(); 
    // some other code 
} 
+3

當然,您可以將一個布爾值傳遞給該函數以指示該值是應該遞增還是遞減。 –

+4

'this.add(1)','this.add(-1)'。 – Bergi

+0

爲什麼你需要一個功能來做兩件不同的事情?最好將它們分開,而不是將控制流添加到應該是簡單的東西上。 –

回答

1

@KingFelix有它。只需傳遞布爾值即可。

incrementDecrement(shouldIncrement: boolean) { 
    shouldIncrement ? value++ : value--; 
} 

aceitaProposta() { 
    this.incrementDecrement(true); 
} 

recusaProposta() { 
    this.incrementDecrement(false); 
} 
+0

哦,就是這樣。非常感謝你 –

2

應該很容易。

function incrementDecrement(inc: boolean) 
{ 
    inc ? this.prop++ : this.prop--; 
} 
+1

不妨是'this.prop + = inc - !inc;'爲了清楚起見,使用'if' /'else'語句。 – Bergi

+0

他們用角度標記了這個問題,所以我認爲在這裏也可以顯示TypeScript答案。 – zigzag

1

另一種做法是使用ES6和更多'功能'代碼。使參數成爲一個函數而不是布爾值。然後在你傳遞的函數中進行更改。

update(alteration) { 
    x = alteration(x); 
} 

aceitaProposta() { 
    this.update((x) => x - 1); 
} 

recusalProposta() { 
    this.update((x) => x + 1); 
} 

沒有ES6它有點醜,但你只是在匿名函數聲明中添加。