본문 바로가기

JS

(JS) ECMA 262 - TC39 new feature 2022.6 version

ECMAScript 2022, the 13th edition, introduced top-level await, allowing the keyword to be used at the top level of modules; new class elements: public and private instance fields, public and private static fields, private instance methods and accessors, and private static methods and accessors; static blocks inside classes, to perform per-class evaluation initialization; the #x in obj syntax, to test for presence of private fields on objects; regular expression match indices via the /d flag, which provides start and end indices for matched substrings; the cause property on Error objects, which can be used to record a causation chain in errors; the at method for Strings, Arrays, and TypedArrays, which allows relative indexing; and Object.hasOwn, a convenient alternative to Object.prototype.hasOwnProperty.

 

 

1. top level await

await 키워드는 async와 함께 사용했어야 하는데

이제 모듈의 최상위(top-level)에서 await를 사용할 수 있다.

 

더 이상 비동기 동작을 위해 async 키워드를 사용할 필요가 없다.

 

before

(async function() {
  await startServer() {
 })();

 

after

await startServer();

 

 

2. new class element

 

1) private 함수나 변수 선언

이제 JS도 Java 처럼 클래스 안에

private 메서드(함수)나 멤버변수(변수)를 가질 수 있게 되었다. 

 

priavate 함수나 변수를 만들려면 이름 앞에 # 기호를 사용하면 된다.

 

class Message {
  #destruct() {
    console.log("boo");
  }
}

const btn = new Messae();
btn.#destruct(); // not invoked

위의 코드 btn.#destruct() 는

Java 클래스의 private 메서드나 멤버변수 처럼

호출되지 않게 된다.

 

class Message {
  #text = "Hi";
}

또한 속성 초기화를 위해

constructor 함수를 사용할 필요도 없어졌다.

 

2) static 메서드

static 키워드를 사용하여 정적 메서드를 사용할 수 있게 되었다.

 

before

class Message {

}

Message.build() {
 
}

 

after

class Message {
  static build() {
  
  }
}

원하면 # 를 build 앞에 붙일 수 있다.

 

 

3. error.cause

error 에 cause 속성을 사용하여 error 원인을 표시할 수 있게 되었다.

const err = new Error("can't save comment", { cause: "not allowed"})

err.mesage; //can't save comment
err.cause; //not allowed

 

4. .at 메서드

at() 활용하여  문자열과 배열의 인덱스에 접근할 수 있게 되었다.

 

const foot = ["pizza", "chicken", "soda"];

food.at(-1) //soda

[ ] 대괄호와 다른 점은 뒤에서도 접근이 가능하다는 것이다.