我创建了具有多个属性的 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/