0

I created ES6 class which has several properties. Like this :

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   

As seen in above code, each property is bonded to the localStorage object. Now, I want one generic method which fetches all getter/setter properties and removes it from localStorage.

So, for that I wrote following method inside the class:

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

But it is not fetching any getter/setter properties. Can anyone tell me where I am wrong?

Hardipsinh Jadeja
  • 1,180
  • 1
  • 13
  • 30
  • Aren't your localStorage keys hashed anyway, so that the name of the instance property doesn't help? – Bergi Dec 05 '17 at 14:13
  • I don't see why you are using those underscore-prefixed properties - they're not even caching anything. Wouldn't local variables be more effective? – Bergi Dec 05 '17 at 14:22

1 Answers1

1

The problem is that getters/setters are not enumerable (like basically anything defined in a class). You can still iterate them through Object.getOwnPropertyNames though. In your case:

removeAll() {
    for (const name of Object.getOwnPropertyNames(CustomLocalStorage.prototype))
        if (name.startsWith("remove_")) // not "removeAll"!
            this[name]();
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375