🫒Public Class Field

In JavaScript, a "public class field" refers to a property or method that is directly attached to a class and can be accessed from any part of the program, both inside and outside the class. This is in contrast to a "private class field," which can only be accessed within the class itself. Public class fields are declared using the constructor method or directly in the class body, and can be accessed using the this keyword. For example:

Copy codeclass MyClass {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

let myObject = new MyClass("John");
console.log(myObject.name); // "John"
myObject.sayName(); // "John"

In the example above, name and sayName are public class fields that can be accessed from anywhere.

It's worth noting that as of ECMAScript 2020 (ES11) version of javascript, it introduced a new syntax called public class fields which allows you to declare fields directly in the class body.

Copy codeclass MyClass {
  publicName = "John";
  public sayName() {
    console.log(this.publicName);
  }
}

let myObject = new MyClass();
console.log(myObject.publicName); // "John"
myObject.sayName(); // "John"

It's also worth noting that this feature is not supported by all JavaScript engines and requires a transpilation step for older browsers.

Last updated