240818-deepdive / javascript-deep-dive

javascript deep dive 스터디 레포 입니다
0 stars 0 forks source link

[info][chapter25] class와 관련한 tc39의 변경사항 #19

Closed paengjiwoo closed 2 weeks ago

paengjiwoo commented 2 weeks ago

private, static 필드 등과 관련해 '2021년 1월 현재 stage 3(candidate)에 제안되어 있다.`는 문장이 있어 이후 tc39 프로세스에 어떤 변화가 있었는지 그리고 class와 관련한 또 다른 변경사항이 있었는지 궁금증이 생겼습니다.

1. Static Class Features (Stage 4, ES2022에 포함)

정적 필드, 정적 private 필드, 정적 메서드를 클래스에 직접 선언할 수 있다는 제안이 stage 4(finished)로 완료되었습니다.

class StaticFeatureExample {
  static staticField = 'I am a static field';
  static #privateStaticField = 'I am a private static field';

  static staticMethod() {
    console.log('I am a static method');
    console.log(this.#privateStaticField);
  }
}

console.log(StaticFeatureExample.staticField);
StaticFeatureExample.staticMethod();

2. Private Field (Stage 4, ES2022에 포함)

private 필드, private 메서드와 접근자 private 선언, 인스턴스 식별을 위한 편리한 검사 등이 stage 4(finished)로 ES2022에 포함되어 완료되었습니다.

class PrivateFieldsExample {
  // 1. Private 필드
  #privateField = 'I am private';

  // 2. Private 메서드
  #privateMethod() {
    return 'This is a private method';
  }

  // Private 접근자
  get #privateGetter() {
    return 'This is a private getter';
  }

  set #privateSetter(value) {
    console.log(`Setting private value: ${value}`);
  }
}

const instance = new PrivateFieldsExample();

// 편리한 검사 사용
console.log(PrivateFieldsExample.hasPrivateField(instance)); // true
console.log(PrivateFieldsExample.hasPrivateField({})); // false

3. Class Static Block (ES2022)

클래스의 정적 초기화 로직을 위한 별도의 블록을 제공합니다. 해당 내용은 stage 4(finished)로 ES2022에 포함되어 완료되었습니다.

class StaticBlockExample {
  static {
    console.log('This is a static initialization block');
    this.staticProp = 'Initialized in static block';
  }
}

console.log(StaticBlockExample.staticProp);

4. Decorators (Stage 3)

클래스, 메서드, 접근자, 필드 등에 메타프로그래밍 기능을 추가할 수 있는 문법으로, 코드의 재사용성과 가독성을 높일 수 있습니다. 해당 문법은 현재 stage 3 상태입니다.

function logged(value, { kind, name }) {
  if (kind === "method") {
    return function (...args) {
      console.log(`Calling ${name} with arguments:`, args);
      return value.call(this, ...args);
    };
  }
}

class DecoratorExample {
  @logged
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

const decoratorInstance = new DecoratorExample();
decoratorInstance.greet("World");

[JavaScript] Decorator


참고

souplim commented 2 weeks ago

tc39 지우: https://ahnheejong.name/articles/ecmascript-tc39/

데코레이터 제인: https://www.typescriptlang.org/ko/docs/handbook/decorators.html