2017-12-05 17 views
0

몇 가지 속성이있는 ES6 클래스를 만들었습니다. 이와 같이 :ES6 javascript 클래스의 일반 메서드 내에서 모든 getter setter 특성 목록 또는 배열을 가져 오는 방법은 무엇입니까?

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); 
     } 
    } 
} 

을하지만 어떤 게터/setter 속성을 가져 오는되지 않습니다

그래서, 내가 클래스 내부에 다음과 같은 방법을 썼다. 아무도 내가 틀린 곳이라고 말할 수 있습니까?

+0

어쨌든 localStorage 키가 해시되지 않으므로 인스턴스 속성의 이름이 도움이되지 않습니까? – Bergi

+0

왜 밑줄 접두어로 된 속성을 사용하고 있는지 알지 못합니다. 아무 것도 캐싱하지도 않습니다. 지역 변수가 더 효과적이지 않습니까? – Bergi

답변

1

문제는 getters/setters are not enumerable입니다 (기본적으로는 class에 정의 된 것과 같습니다). 그래도 여전히 iterate them through Object.getOwnPropertyNames 일 수 있습니다. 귀하의 경우 :

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

코드에 대한 귀하의 생각에 감사드립니다. 당신의 도움을 주셔서 감사합니다 –