[Javascript] Private class field & method (`#` 붙이기)

허션·2025년 9월 5일
0

공부

목록 보기
11/13
post-thumbnail

원래는 javascript에 private class field를 정의하는 문법이 없어서, instance variable의 이름 앞에 _(underbar)을 붙이는 식으로만 했다. (실제 기능 X)

➡️ 이제는 instance variable 이름 앞에 #을 부티면 private field로 취급된다.

  • private class field는 constructor 안에서 선언될 수 없고, 밖에서 선언된 이후 constructor에서 값을 할당하는 식으로 진행되어야 한다.

     class User {
          #votingAge;
    
          constructor(){
               this.#votingAge = 18;
          }
     } 
  • private class field의 유용한 점 :
    class 바깥에서 field의 값을 임의로 수정할 수 없다.
    합법적인 수정 경로인 setter 함수를 정의해준다면 가능하다.
    또한, setter 함수에서 값에 대한 제약을 걸어두기 용이하다.

    class User {
      #votingAge = 18;
      
      get votingAge(){ return this.#votingAge;}
    
      set votingAge(age) {
           if (age>= 18) this.#votingAge = age;
      }
       }
    
      const user = new User();
      user.votingAge = 10; // invalid
      console.log(user.votingAge); // still 18
      user.votingAge = 20; // meets check
      console.log(user.votingAge); // changed to 20
    

    Private class method :
    => class instance method의 이름 앞에도 #를 붙이면 private class method가 되어서 class 정의 내부에서만 사용 가능하다.

profile
다시해보자.

0개의 댓글