javascript - 在 JS 中泛化多个 get 函数
问题描述
我有一个 JS 类,它有一堆 get 方法,它们都有相同的结构来调用 JSON 对象值,我怎样才能概括这个函数,因为我需要数百个 get 函数,所以不必为每个 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()
推荐阅读
- processing - 处理:如何修复计时器显示以及如何在游戏结束时显示时间分数?
- next.js - 在源代码中不可见的 Next js 上更新的 Head 部分
- python-3.x - Flask - TypeError:类型循环的对象不是 JSON 可序列化的
- php - 如何从多维数组中删除php中特定键的重复值
- javascript - javascript 对象被定义然后它是未定义的。对象和函数共享同一个对象
- javascript - 使用公共 api 将数据提取到我的 html 页面中。需要帮助找出要提取的对象的名称
- linux - 在这些 tar 和 gzip 命令中,独立的“-”有什么作用?
- xfs - 我如何知道是否完成了现金加载/现金补充操作
- .net - 从我的 .NET 应用程序的安装程序中诊断丢失的 DLL/程序集的更好方法是什么?
- ios - 试图将 Compositional Layout CollectionView 与 PageControl 连接起来。visibleItemsInvalidationHandler 没有调用