JavaScript/Public fields
[i]Learn· Using classes

Public fields

Private fields also have their public counterparts, which allow every instance to have a property. Fields are usually designed to be independent of the constructor's parameters.

class MyClass {
  luckyNumber = Math.random();
}
console.log(new MyClass().luckyNumber); // 0.5
console.log(new MyClass().luckyNumber); // 0.3

Public fields are almost equivalent to assigning a property to this. For example, the above example can also be converted to:

class MyClass {
  constructor() {
    this.luckyNumber = Math.random();
  }
}
Source: Using classes by Mozilla Contributors, licensed under CC-BY-SA-2.5. Retrieved 2026-11-18. Changes: Extracted the section "Public fields"; removed the code-block language labels; made links absolute; examples are the page's own code blocks, unchanged.