javascript - 如何在 ES6 javascript 类中的泛型方法中获取所有 getter setter 属性的列表或数组?

标签 javascript local-storage es6-class

我创建了具有多个属性的 ES6 类。像这样:

class CustomLocalStorage {
//#region userName
get userName() {
    this._userName = localStorage.getItem("25ciWC16Hh");
    this._userName = this._userName ? decryptText(this._userName) : "";
    return this._userName;
}

set userName(newValue) {
    if(newValue) {
        this._userName = encryptText(newValue + "");
        localStorage.setItem("25ciWC16Hh", this._userName);
    }

}
remove_userName() {
    this._userName = null;
    localStorage.removeItem("25ciWC16Hh");
}
//#endregion userName

//#region webapi
get webapi() {
    this._webapi = localStorage.getItem("ALOrVJuVKt");
    this._webapi = this._webapi;
    return this._webapi;
}

set webapi(newValue) {
    this._webapi = newValue;
    localStorage.setItem("ALOrVJuVKt", this._webapi)
}
remove_webapi() {
    this._webapi = null;
    localStorage.removeItem("ALOrVJuVKt");
}
//#endregion webapi   

如上面的代码所示,每个属性都绑定(bind)到 localStorage 对象。现在,我想要一种通用方法来获取所有 getter/setter 属性并将其从 localStorage 中删除。

因此,为此我在类中编写了以下方法:

removeAll() {
    for (var key in this) {
        if(key != "_settings" && key != "") {
            this[key] = null;
            localStorage.remove(key);
        }
    }
}

但它没有获取任何 getter/setter 属性。谁能告诉我哪里错了?

最佳答案

问题是 getters/setters are not enumerable (基本上就像类中定义的任何内容一样)。您仍然可以iterate them through Object.getOwnPropertyNames尽管。对于您的情况:

removeAll() {
    for (const name of Object.getOwnPropertyNames(CustomLocalStorage.prototype))
        if (name.startsWith("remove_")) // not "removeAll"!
            this[name]();
}

关于javascript - 如何在 ES6 javascript 类中的泛型方法中获取所有 getter setter 属性的列表或数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47655585/

相关文章:

javascript - jQuery addClass 没有效果

javascript - 如何等到 localStorage.setItem 在 Angular 4 中完成

javascript - 返回 this 的 ES6 类方法无法由 stderr.on ('data' 调用)

reactjs - React/ES6 -> 如何从另一个组件调用 React 组件类方法?

javascript - 固定 AppBar 下的内容

javascript - 如何将 $scope 传递给 $factory

google-chrome-extension - 从 localStorage 迁移到 chrome.storage

javascript - 在 javascript 库中的导出类之外声明函数是实现私有(private)函数的好习惯吗?

javascript - Google Analytics 是否具有用于长时间运行的 Web 应用程序的 "heartbeat"函数?

javascript - Angular : best way to provide local storage data? 在每个 Controller 中设置 rootScope?