Javascript Class instance member Fields
ES13 introduced public and private properties like other programming languages. ES06 introduced classes to javascript and class properties are defined in the constructor
In the below example, the 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 was introduced to add public and private fields as seen below
We can define these properties as part of class level private files are declared 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 a keyword that applies to fields and methods of a class in javascript.
These can be accessed without an instance of a class Static fields are applied to the class level.
Static can be applied.
- properties
- methods
- blocks
if a variable is declared as static, called a static field in javascript. if there are multiple objects for the same class, there is only one value exists for all classes That means It is a common and global field value applicable to all instances of a class
Real-world use cases is a school name for all students and teachers.
class student{
name;
schoolName="Abc school"
}
if there are 1000 students, the schoolName property is repeated and allocated to 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 a static variable by adding # symbol at the start
class student{
name;
static #schoolName="Abc school"
}
Let’s see static methods.
the static keyword is applied to the method
Here is a public static method
class student{
let name;
static #schoolName="Abc school"
static getSchoolName() {
return #schoolName
}
Here is a private static method
class student{
let name;
static #schoolName="Abc school"
static #getSchoolName() {
return #schoolName
}