ES2022 クラスフィールド宣言のサンプル

環境
Google Chrome 123.0.6312.86(Official Build) (64 ビット)
Windows 11 Pro 64bit

概要
ES2022からは、他言語と同じようにクラスフィールド宣言ができるようになります。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Student {
age = 23;
}
const st = new Student();
console.log(st.age);
class Student { age = 23; } const st = new Student(); console.log(st.age);
class Student {
  age = 23;
}

const st = new Student();
console.log(st.age);

結果 23

従来のフィールド

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Student {
constructor() {
this.age = 19;
}
}
const stu = new Student();
console.log(stu.age);
class Student { constructor() { this.age = 19; } } const stu = new Student(); console.log(stu.age);
class Student {
  constructor() {
    this.age = 19;
  }
}

const stu = new Student();
console.log(stu.age); 

結果 19

スタティックなクラスフィールド宣言
静的な(スタティックな)クラスフィールド宣言もできるようになります。
インスタンス化なしでクラスのフィールドにアクセスできます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Student {
static category = "good"
}
console.log(Student.category);
class Student { static category = "good" } console.log(Student.category);
class Student {
  static category = "good"
}

console.log(Student.category);

 

IT

Posted by arkgame