JS: Class static fields and methods

By Xah Lee. Date: . Last updated: .

Class members can be declared with a static keyword in front.

For example

Static members becomes properties of the class constructor function.

Example

// verify static member behavior of a class

class Burger {
 static bread = 2;

 static add_bread(x) {
  console.log("add_bread called with arg " + x);
  Burger.bread = Burger.bread + x;
 }
}

// s------------------------------

// all static members are properties of the constructor

// has property bread
console.assert(
 Object.hasOwn(Burger, "bread"),
);

// has property add_bread
console.assert(
 Object.hasOwn(Burger, "add_bread"),
);