Class Fields

ES13 introduced public and private properties like other programming languages. ES06 introduced classes to javascript and class properties are defined in constructor

In the below example, Employee class has three fields id,name and salary.

class Employee  {
  
  constructor() {
    this.name = "john"
    this.id = 12
    this.salary=5000
  }
}

const employee = new Employee()
employee.name = "Eric" 
console.log(employee.id)
button.id =11

ES2022 introduced to add public and private fields as seen below

We can define these properties as part of class level private files are declared with starting with # and variable name

class Employee  {
      name = "john"
    id = 12
    #salary=5000
  constructor() {

  }
}

const employee = new Employee()
employee.name = "Eric" 
console.log(employee.id)
button.id =11

Static class fields and private static methods:

Static is an keyword which applies to fileds and methods of a class in javascript.

These can be accessed without instance of an class Static fields are applied to class level.

Static can be applied

  • properties
  • methods
  • blocks

if an variable is declared as a static, called static field in javascript. if there are multiple for objects for the same class, There is only one value exists for all classes That means, It is a common and global filed value applicable to all instance of an class

Real world use cases is an school name for all students and teachers.

class student{
  
  name;
  schoolName="Abc school"
}

if there are 1000 students, schoolName property is repeated and allocated an memory.

To reduce the usage of memory, Static fields are introduced

class student{
  
  name;
 static schoolName="Abc school"
}

In the above schoolName is public static property

Let’s change this property to private

declare static variable with adding # symbol at start

class student{
  
  name;
 static #schoolName="Abc school"
}

Let’s see static methods

static keyword is applied to method

Here is an public static method

class student{
  
 let name;
 static #schoolName="Abc school"

  static getSchoolName() {
    return #schoolName
  }

Here is an private static method

class student{

let name;
static #schoolName="Abc school"

static #getSchoolName() {
  return #schoolName
}