반응형
정의 및 예시
#은 ECMAScript 2022(ES2022)버전에서 클래스안에 프라이빗 필드와 메서드를 정의할 수 있는 기능입니다.
해당 기능을 사용하면 클래스 내부에서만 접근 가능한 멤버를 쉽게 만들 수 있어서, 코드의 캡슐화와 보안을 강화하는 데 유용합니다.
예제 (Vanilla JS)
class User {
#name; // 프라이빗 필드
constructor(name) {
this.#name = name;
}
#greet() { // 프라이빗 메서드
return `Hello, ${this.#name}!`;
}
sayHello() {
return this.#greet();
}
}
const user = new User("Alice");
console.log(user.sayHello()); // "Hello, Alice!"
console.log(user.#name); // SyntaxError: Private field '#name' must be declared in an enclosing class
user.#greet(); // SyntaxError: Private field '#greet' must be declared in an enclosing class
예제(typescript)
class User {
// 프라이빗 필드를 선언할 때 타입을 명시
#name: string;
// 생성자에서 매개변수의 타입을 명시
constructor(name: string) {
this.#name = name;
}
// 프라이빗 메서드에서도 반환 타입을 명시
#greet(): string {
return `Hello, ${this.#name}!`;
}
// 퍼블릭 메서드의 반환 타입을 명시
sayHello(): string {
return this.#greet();
}
}
const user = new User("Alice");
console.log(user.sayHello()); // "Hello, Alice!"
예제3
class BankAccount {
#balance; // 프라이빗 필드
#accountNumber; // 프라이빗 필드
constructor(accountNumber, initialBalance) {
this.#accountNumber = accountNumber;
this.#balance = initialBalance;
}
#validateAmount(amount) { // 프라이빗 메서드
if (amount <= 0) {
throw new Error("Amount must be greater than zero");
}
}
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
return this.#balance;
}
withdraw(amount) {
this.#validateAmount(amount);
if (amount > this.#balance) {
throw new Error("Insufficient funds");
}
this.#balance -= amount;
return this.#balance;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount("123456789", 1000);
console.log(account.deposit(500)); // 1500
console.log(account.withdraw(200)); // 1300
console.log(account.getBalance()); // 1300
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
ECMA2022를 사용하기 위한 babel 셋팅
1. babel 설치: 먼저 babel 과 필요한 프리셋을 설치합니다.
npm install @babel/core @babel/cli @babel/preset-env @babel/node --save-dev
2. babelrc or .babel.config.json 파일 설정
- @babel/preset-env 설정
- targets: Babel이 어떤 환경을 대상으로 코드를 변환할지 설정합니다. 위의 설정에서는 ES 모듈을 지원하는 환경을 대상으로 합니다.
- 최신 JavaScript 기능을 포함한 코드 변환을 위해 @babel/preset-env를 사용합니다. @babel/preset-env는 최신 ECMAScript 표준에 맞게 필요한 Babel 플러그인들을 자동으로 설정합니다.
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}
3. 코드 컴파일 및 실행
-스크립트 추가: package.json 파일에 babel을 사용하여 코드를 컴파일 하고 실행하는 스크립트를 추가합니다.
{
"scripts": {
"build": "babel src -d dist",
"start: "node dist/index.js"
}
}
Nuxt.js와 같은 프레임워크를 사용하면 Babel과 같은 도구는 이미 내장되어 있어 내부적으로 babel을 사용하여 코드 변환 처리하기에 별도로 설정할 필요가 없습니다
단 , 필요에 따라 nuxt.config.js 파일에서 사용자 정의할 수 있습니다. 예를 들어, 특정 Babel 플러그인을 추가하려면 build 옵션을 사용하여 사용자정의를 추가합니다.
export default {
...기타설정
build: {
babel: {
plugins: [
// 필요한 Babel 플러그인 추가
["@babel/plugin-proposal-private-methods", { "loose": true }]
]
}
}
}
만약 typescript 를 사용한다면?
- typescript 컴파일러 설정
- 이 코드를 컴파일하기 위해서는 TypeScript 컴파일러가 필요합니다. 이를 위해 tsconfig.json 파일을 설정해야 합니다.
// 타입스크립트 설정 예시(tsconfig.json)
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
반응형
'내직업은 IT종사자 > javascript' 카테고리의 다른 글
useRoute()로 라우팅 정보 가져오기 (0) | 2024.10.15 |
---|---|
lodash 라이브러리 chunk 란? (0) | 2024.10.11 |
ealry return 은 좋은 것일까? (0) | 2024.05.08 |
블로킹(Blocking)과 논블로킹(Non-blocking) 그리고 동기(synchronous) 과 비동기(asynchronous)의 정의 및 차이점 (헷갈리지않기!) (2) | 2024.05.01 |
1차원 객체를 spread operator(스프레드 연산자)로 복사하면 얕은 복사 일까 깊은 복사 일까? (0) | 2023.12.30 |