javascript中的动态getter和setter

时间:2016-09-09 03:15:13

标签: javascript node.js ecmascript-6

我使用ES6风格的构造,我希望能够做到以下的事情:

class Settings {
    constructor() {
        this.settingsLoaded = false;
        this.settings = {};
        Models.Settings.findAll({ raw: true }).then(settings => {
            settings.forEach(setting => {
                this.settings[setting.name] = setting.value;
            });
            this.settingsLoaded = true;
        });
    }
    get [*]() {
        return this.settings[ <called function name goes here> ];
    }
    set [*](value) {
        Models.Settings.findOrCreate({where: {name: <called function name goes here> }}).spread((setting, created) => {
            setting.value = value;
            setting.save();
        });
        this.settings[settingName] = newValue;
    }
}
var settings = new Settings();
module.exports = settings;

然后我可以做以下事情:

console.log(settings['Name']); // Returns "Me"
settings.Name = "You";
console.log(settings['Name']); // Returns "You"
console.log(settings.notsetyet); // Returns "undefined"
settings["notsetyet"] = JSON.stringify(['things', 'go better', 'with brackets']);
console.log(settings.notsetyet); // Returns "['things','go better','with brackets']"

未定义空或未使用的变量,正如预期的那样,正确地返回填充值,并且分配新变量(或更新现有变量)将使用sequelize将更改保留回数据库。整个事情应该是一个单身人士,因此线程之间没有竞争条件。

0 个答案:

没有答案