private field 선언
- # prefix를 사용하여 field 명을 정의하는 경우 private field 로 사용할 수 있습니다.
- private 필드는 사용전에 선언되어야 합니다.
[example]
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
let r = new Rectangle(10, 20);
console.log(r); // RectangleTest {height: 10, width: 20}
// class field 값 변경가능
r.height = 20;
console.log(r); // RectangleTest {height: 20, width: 20}
// private field 정의
class Rectangle {
#height = 0;
#width;
constructor(height, width) {
this.#height = height;
this.#width = width;
// delete this.#height; // Uncaught SyntaxError: Private fields can not be deleted
// this.#height = 10; // Uncaught SyntaxError: Identifier 'Rectangle' has already been declared
}
}
let r = new Rectangle(10, 20);
// 접근불가
r.height; // undefined
[References]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes
Classes - JavaScript | MDN
Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의
developer.mozilla.org
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/Private_class_fields
Private class fields - JavaScript | MDN
class 의 속성(property)들은 기본적으로 public 하며 class 외부에서 읽히고 수정될 수 있다. 하지만, ES2019 에서는 해쉬 # prefix 를 추가해 private class 필드를 선언할 수 있게 되었다.
developer.mozilla.org
https://ui.toast.com/weekly-pick/ko_20200312
은닉을 향한 자바스크립트의 여정
ECMAScript 클래스 필드(class field) 명세중에 `Private field` 즉 `Private Property` (이하 Private 속성) 가 있다. 클래스 필드 스펙은 Stage 3(Candidate)까지 올랐으니 아마 곧 Stage 4(Finished)를 거쳐 표준 스펙이 될
ui.toast.com
'JavaScript' 카테고리의 다른 글
[JavaScript] 객체 수정 제한 (const, Object.freeze(), Object.seal(), Object.preventExtensions()) (0) | 2022.10.05 |
---|---|
[JavaScript] 자바스크립트 단점 (0) | 2022.10.05 |
[JavaScript] 프로토타입(prototype) (0) | 2022.08.11 |
[JavaScript] 동기 & 비동기 (0) | 2020.08.27 |