ES2022

1.멤버변수(클래스필드) 선언방식이 간단하게 바뀜

constructor()로 멤버변수(클래스필드)를 선언하던 기존의 방식에서 아래와 같이 바뀜

// 새로운 방식
class Human {
  age = 18;
  static category = "animal"
}

let user = new Human();
user.age; // 18
user.category; // undefiend


// 기존방식
class Human {
  constructor() {
    this.age = 18;
  }
}

const human = new Human();
console.log(human.age); // 18

2.정적(static)으로 멤버변수(클래스필드) 선언 가능

static으로 클래스에 멤버변수를 선언한후 생성자 생성없이 바로 사용 가능

class Human {
  static category = "animal"
}

console.log(Human.category);  // animal

3.프라이빗(private)으로 멤버변수(클래스필드) 선언과 함수사용이 가능

private으로 생성한 변수와 함수는 클래스 내부에서 사용이 가능하다

그러나 외부에서는 사용이 불가하다

class MyClass {
  #foo = "ラーメン";
  
  #bar() {
    console.log("うどん")
  }
}

let myCls = new MyClass();
myCls.#foo; // Uncaught SyntaxError: Private field '#foo' must be declared in an enclosing class
myCls.#bar; // Uncaught SyntaxError: Private field '#bar' must be declared in an enclosing class

Private를 사용한 예제

아래의 예제에서 #name의 값을 직접 접근해서 바꾸는건 불가능하다

변경을 위해서는 함수등을 사용해야한다

class MyClass {
  // プライベートなフィールド
  #name;
  
  constructor(name) {
    this.#name = name
  }

  hello() {
    console.log(`こんにちは${this.#name}さん!`)
  }
  
  changeName(cname){
    this.#name=cname;
  }
}

const foo = new MyClass("田中");
foo.hello(); // 「こんにちは田中さん!」と出力される
foo.#name = '中村'; // Uncaught SyntaxError: Private field '#name' must be declared in an enclosing class
foo.changeName('中村');
foo.hello(); // 「こんにちは中村さん!」と出力される

4.Async선언없이 Await를 사용가능하게 된다

제일 바깥쪽의 함수에서 async없이 await를 사용하는 등의 사용이 가능하다

모듈안에서만 사용 가능하다 (type="module")

// 신규 방식
await new Promise((resolve) => {
  setTimeout(() => {
    alert("3초 경과했습니다");
    resolve();
  }, 3000);
});

// 기존 방식
// async로 한번 감싸준 후 재호출한다
const main = async () => {
  await new Promise((resolve) => {
    setTimeout(() => {
      alert("한번 감싸줬어요");
      resolve();
    }, 1000);
  });
}

main();

5. at()함수를 이용해서 특정 배열의 요소를 취득가능

배열의 마지막 요소를 쉽게 취득가능하게 되었다

// 1.배열의 마지막 요소를 취득하는경우

// 신규 방식
const myArray = ["りんご", "バナナ", "ぶどう"];
console.log(myArray.at(-1)); // ぶどう


// 기존 방식
const myArray = ["りんご", "バナナ", "ぶどう"];
console.log(myArray[myArray.length - 1]); // ぶどう

// 2. 문자열에도 사용가능하다
"테스트".at(2) // 트

6. 프로퍼티 확인에 hasOwn()을 사용

기존에 클래스의 프로퍼티 확인에 hasOwnProperty를 사용했지만 hasOwn()을 사용하여 더욱 간단하게 사용가능해짐

const myObject = {
  name: "鈴木",
  hasOwnProperty: () => {
    return false;
  },
}

console.log(Object.hasOwn(myObject, "name"));
// true


참조

https://zenn.dev/moneyforward/articles/es2022-whats-new?redirected=1

https://www.tohoho-web.com/ex/es2022.html

Feb 25, 2023 Views 99