我想創建一個具有屬性的物件,有些屬性需要用兩種類似的方法處理,如何在不重復代碼的情況下使其達到最優?這是物件的示例,它似乎是使它變得更簡單的方法..有什么建議嗎?!
const points = {
sum : 10,
offense : 0,
defense: 0,
support: 0,
addOffense(){
if (this.sum > 0) {
this.sum--;
this.offense ;
}
return this;
},
subtractOffense(){
if (this.offense > 0) {
this.offense--;
this.sum ;
}
return this;
},
addDefense(){
if (this.sum > 0) {
this.sum--;
this.offense ;
}
return this;
},
subtractDefense(){
if (this.offense > 0) {
this.offense--;
this.sum ;
}
return this;
},
addSupport(){
if (this.sum > 0) {
this.sum--;
this.offense ;
}
return this;
},
subtractSupport(){
if (this.offense > 0) {
this.offense--;
this.sum ;
}
return this;
}
}
console.log(points.addOffense().offense)
我只想制作 2 種方法而不是重復 6 種方法,但是如何正確地將我想要使用的屬性傳遞給方法以及如何在外部使用它們?!如果您知道如何做到這一點,請使用代碼示例……因為您真的也想了解正確的語法!
uj5u.com熱心網友回復:
使用動態屬性名稱來合并類似的邏輯。考慮只有一個addandsubtract方法,它接受一個引數 - offense、defense或support。驗證引數是那些允許的道具之一,然后驗證點可用于加法或減法,然后您可以使用括號表示法從總和和動態道具中加減。
const points = {
sum : 10,
offense : 0,
defense: 0,
support: 0,
validate(prop) {
// A type-aware system would be better than this, if possible
if (prop !== 'offense' && prop !== 'defense' && prop !== 'support') {
throw new Error('Invalid prop');
}
},
subtract(prop) {
this.validate(prop);
if (this[prop] === 0) {
// no change; at minimum
return this;
}
this[prop] -= 1;
this.sum = 1;
return this;
},
add(prop) {
this.validate(prop);
if (this.sum === 0) {
// no change; can't remove from sum any more
return this;
}
this[prop] = 1;
this.sum -= 1;
return this;
}
};
const result = points
.add('offense') // 1
.add('offense')
.add('offense')
.add('offense')
.add('offense')
.add('offense')
.add('offense') // 7
.subtract('offense')
.subtract('offense') // 5
.add('offense')
.add('offense')
.add('offense')
.add('offense')
.add('offense') // 10
.add('defense') // past sum
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537312.html
上一篇:在具有多個值的物件的子陣列中搜索
