Frontend/Javascript

ES2022 (ES13) Class Fields 변경된 내용

Developer Mobssie 2022. 8. 19. 12:11

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