JS: ECMAScript 2022

By Xah Lee. Date: . Last updated: .

Class allows defining property (now known as fields)

now you can define properties in class, instead of this.name in constructor.

class AA {
 static cat = 7;
 dog = 5;
}

console.assert(Object.hasOwn(AA, "cat"));

const xobj = new AA();

console.assert(Object.hasOwn(xobj, "dog"));

Private field and methods in class

now you can have private variable or methods inside the class, known as private fields, private methods. in general, private elements.

private element names start with a hash #.

class AA {
 // private static field
 static #cat = 7;

 static get_cat() {
  return AA.#cat;
 }

 // private instance field
 #dog = 5;

 get_dog() {
  return this.#dog;
 }
}

console.assert(AA.get_cat() === 7);

const xobj = new AA();

console.assert(xobj.get_dog() === 5);

Before ECMAScript 2022 , keyword class is just a convenient syntax. Everything thing you can do with keyword class can be written without.

Since ECMAScript 2022, it added a new feature of private members. Now, the only way to define a constructor with private members is by using the keyword class.

Test private field existance [#x in obj]

syntax #x in obj to test for private fields on objects

class AA {
 // private field
 #xpriv;

 // test for private field existance
 static isAA(xobj) {
  return #xpriv in xobj;
 }
}

console.assert(AA.isAA(new AA()) === true);

// s------------------------------
// test if it works on private field of the same name but in different object

class BB {
 #xpriv;
}

console.assert(AA.isAA(new BB()) === false);

Static block inside class

A Class Static Block is a syntax that lets the class run a block of code when a class definition is evaluated.

class Xclass {
 static {
  console.log("i ran!");
 }
}
// i ran!
xtodo

Others

Reference