[英]Generalizing multiple get functions in JS
我有一個 JS 類,它有一堆 get 方法,它們都有相同的結構來調用 JSON 對象值,我如何概括這個函數,因為我需要數百個這樣的方法,而不必為每個 get 函數編寫一個方法使用相同的代碼。
get Health() {
var temp = this._foods[this._foodID].Health;
return temp === undefined ? 0 : temp;
};
get HealthRegen() {
var temp = this._foods[this._foodID].HealthRegen;
return temp === undefined ? 0 : temp;
};
您可以像這樣在this._foods
對象上創建一個代理:
class SomeClass { constructor() { this._foodID = 1; this._foods = { 1: { Health: 1, HealthRegen: 1 }, 2: { Health: 2 }, }; this.proxy = new Proxy(this._foods, { get: (object, key) => { const value = object[this._foodID][key]; return value === undefined ? 0 : value; } }); } someMethod() { console.log('someMethod call') } } const someInstance = new SomeClass(); console.log(someInstance._foodID); console.log(someInstance.proxy.Health); console.log(someInstance.proxy.HealthRegen); console.log(someInstance.proxy.UndefinedProperty); someInstance._foodID = 2; console.log(someInstance._foodID); console.log(someInstance.proxy.Health); console.log(someInstance.proxy.HealthRegen); console.log(someInstance.proxy.UndefinedProperty); someInstance.someMethod()
定義一個將屬性名稱作為參數的方法,並從每個 getter 中調用它。
_getProp(propname) {
var temp = this._foods[this.__foodId][propname];
return temp === undefined ? 0 : temp;
}
get Health() {
return this._getProp("Health");
};
get HealthRegen() {
return this._getProp("HealthRegen");
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.