Class Public Instance Fields & Private Instance Fields
before
class ColorButton extends HTMLElement {
constructor() {
this.color = "red"
this._clicked = false
}
}
const button = new ColorButton()
// Public fields can be accessed and changed by anyone
button.color = "blue"
// Curse your sudden but inevitable betrayal
console.log(button._clicked) // Prints: false, can be accessed from the instance
button._clicked = true // Doesn't throw an error, can be read from the instance
after : 필드를 정의와 동시에 초기화가 가능해졌다.
class ColorButton extends HTMLElement {
color = "red"
_clicked = false
}
after : private fields _ 대신 #사용해 프라이빗하게 사용 가능하다.
class ColorButton extends HTMLElement {
// All fields are public by default
color = "red"
// Private fields start with a #, can only be changed from inside the class
#clicked = false
}
const button = new ColorButton()
// Public fields can be accessed and changed by anyone
button.color = "blue"
// SyntaxError here
console.log(button.#clicked) // Cannot be read from outside
button.#clicked = true // Cannot be assigned a value from outside
Private instance methods and accessors
class Banner extends HTMLElement {
// Private variable that cannot be reached directly from outside, but can be modified by the methods inside:
#slogan = "Hello there!"
#counter = 0
// private getters and setters (accessors):
get #slogan() {return #slogan.toUpperCase()}
set #slogan(text) {this.#slogan = text.trim()}
get #counter() {return #counter}
set #counter(value) {this.#counter = value}
constructor() {
super();
this.onmouseover = this.#mouseover.bind(this);
}
// private method:
#mouseover() {
this.#counter = this.#counter++;
this.#slogan = `Hello there! You've been here ${this.#counter} times.`
}
}
https://yagmurcetintas.com/journal/whats-new-in-es2022?ref=morioh.com&utm_source=morioh.com
'Frontend > Javascript' 카테고리의 다른 글
json 응답값 표로 쉽게 정리하기 (0) | 2024.04.12 |
---|---|
PWA - 서비스 워커 웹 캐싱(service worker) (0) | 2023.04.25 |
ES2021 (ES12) Logical assignment operators (논리 할당 연산자) (0) | 2022.08.18 |
[monorepo] nx를 이용하여 App 생성하기 (0) | 2022.08.05 |
[monorepo] 모노레포 nx 설치 (0) | 2022.07.20 |