ECMAScript question detail
Class fields
ES2015 introduced classes to javascript and class properties are defined in the constructor. In the below example, the Employee class has two fields defined in the constructor.
class Employee {
constructor() {
this.name = "John"; //public
this._age=35; //private
}
const employee = new Employee();
employee.name = "Jack";
employee._age =35; //No error
In the above example, the private _age property can be accessed and modified outside of the class. The prefix _ is just a naming convention for private field and won't enforce any strict rule.
ES2022 introduced private and static fields to the classes.
- Public and private fields or methods: ES2022 introduced public and private properties or methods like other programming languages. These properties and methods can be defined outside the constructor and private fields prefixed with # symbol followed by variable name.
In the below example, the Employee class has been defined with private variable outside the constructor.
class Employee {
name = "John";
#age=35;
constructor() {
}
#getAge() {
return #age
}
}
const employee = new Employee();
employee.name = "Jack";
employee.#age = 35; // Throws an error
- Static fields and methods:
Static fields and methods are applied to the class level and they can be accessed without an instance of a class. These fields and methods declared with static keyword
Let's define a employee class with static field and methods declared with static keyword.
class Employee{
name = "John";
static #employerName="Github"
static #getEmployerName() {
return #employerName
}
}
const employee = new Employee();
employee.emp = "Jack";
employee.#employerName = 35; // Throws an error