我创建了具有多个属性的 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
如上面的代码所示,每个属性都绑定到 localStorage 对象。现在,我想要一种通用方法,它获取所有 getter/setter 属性并将其从 localStorage 中删除。
因此,为此我在类中编写了以下方法:
removeAll() {
for (var key in this) {
if(key != "_settings" && key != "") {
this[key] = null;
localStorage.remove(key);
}
}
}
但它没有获取任何 getter/setter 属性。谁能告诉我我错在哪里?
问题是getter/setter 是不可枚举的(基本上就像 a 中定义的任何东西class
)。不过,您仍然可以遍历它们Object.getOwnPropertyNames
。在你的情况下:
removeAll() {
for (const name of Object.getOwnPropertyNames(CustomLocalStorage.prototype))
if (name.startsWith("remove_")) // not "removeAll"!
this[name]();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句