class Human { #age = 10;}const person = new Human();
class Human { #age = 10; getAge() { return this.age; // Error TS2551: Property 'age' does not exist on type 'Human'. // Did you mean '#age'? }}
반드시 선언을 통해서만 만들 수 있고 동적으로 추가할 수 없다.
메서드를 선언할때는 사용할 수 없다.
외부의 게터를 통해 private 속성에 접근할 수 있다.
class Human { #age = 10; getAge() { return this.#age; }}const person = new Human();console.log(person.getAge()); // 10
모든 Private 필드는 소속된 클래스에 고유한 스코프를 갖는다.
class Human { age = 10; getAge() { return this.age; }}class Person extends Human { age = 20; getFakeAge() { return this.age; }}const p = new Person();console.log(p.getAge());console.log(p.getFakeAge());
public 속성이라면 this 컨텍스트에는 age 속성이 하나기 때문에 age의 값이 20이다.
class Human { #age = 10; getAge() { return this.#age; }}class Person extends Human { #age = 20; getFakeAge() { return this.#age; }}const p = new Person();console.log(p.getAge()); // 10console.log(p.getFakeAge()); // 20
기존처럼 인스턴스별로 독립적인 공간을 갖지만, 추가로 클래스 별로 독립적인 공간을 갖는 것이다.
Human 클래스 스코프의 #age와 Person 클래스 스코프의 #age는 다르다.
그러므로 Human 클래스에 속한 getAge()가 실행될때는 Human의 #age에 접근하고 Person의 getFakeAge()가 실행될 때는 Person의 #age에 접근한다.