首页 > 解决方案 > 在 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;
};

标签: javascriptfunction

解决方案


您可以像这样在对象上创建代理: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()


推荐阅读