簡體   English   中英

如何在ES6 javascript類的通用方法中獲取所有getter setter屬性的列表或數組?

[英]How to fetch list or array of all getter setter properies inside generic method in ES6 javascript 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   

如上面的代碼所示,每個屬性都綁定到localStorage對象。 現在,我需要一個通用方法來獲取所有getter / setter屬性並將其從localStorage中刪除。

因此,為此,我在類中編寫了以下方法:

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

但這並沒有獲取任何getter / setter屬性。 誰能告訴我我哪里錯了?

問題在於, getter / setter不能枚舉 (基本上就像在class定義的任何東西一樣)。 您仍然可以通過Object.getOwnPropertyNames對其進行迭代 在您的情況下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM