JavaScript Class Level Fields

06 Dec, 2021
In any object-oriented programming language, classes can have private and public fields. Fields are nothing but variables that hold the information. There are two types of fields in an object-oriented programming language i.e, instance fields and static fields. An instance member belongs to a specific instance. 
Example: If we create 3 instances (objects) there will be 3 copies of instance fields in memory whereas there will ever be only one copy of a static field no matter how many instances we create. In simple words, a static variable is a variable that is common for all objects.
Private Instance fields: By default, all the properties of a Class are public and can be modified outside the class. So, in order to declare a private class field, we need to use a # prefix.
Syntax:
#variableName
Let us look at the example below: 
Javascript
<script>class IncrementCounter {     // Private variable    #value = 0;     // Public variable    Count = 0;     Increment() {        this.#value++;    }} const counter = new IncrementCounter(); // Raises an errorconsole.log(counter.#value); // Calling the increment functioncounter.increment(); // Printing the private variable valueconsole.log(counter.#value);</script>
Output:
console.log(counter.#value); ^SyntaxError: Private field ‘#value’ must be declared in an enclosing class at wrapSafe (internal/modules/cjs/loader.js:1054:16) at Module._compile (internal/modules/cjs/loader.js:1102:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47
Explanation: In the above example, we are declaring a private variable using #. Running the above script will show an error as “Private field ‘#value’ must be declared in an enclosing class” as we are trying to access a private variable outside the class. So we try to get the value by defining a function as below:
Javascript
<script>class IncrementCounter {    #value = 0;     increment() {        this.#value++;    }     value() {         // Returning the value of        // a private variable        return this.#value;    }} const counter = new IncrementCounter(); // Calling the function value()console.log(counter.value()); // Calling the function increment()counter.increment(); // Calling the function value()console.log(counter.value());</script>
Output:  
0
1
Private static fields: A static field can be created by using the keyword static. Sometimes even the static fields are kept hidden, and you can make them private. 
Syntax:
static #staticFieldName
Let us look at the example below: 
Javascript
<script>class User {     // Private static field of string type    static #name = "";     // Private static field    static #age     // Constructor function    Person(user_name, user_age) {        User.#name = user_name;        User.#age = user_age;        return User.#name + ' ' + User.#age;    }} // Create an object user1user1 = new User();console.log(user1.Person("John", 45)); // Create an object user2user2 = new User()console.log(user1.Person("Mark", 35));</script>
Output:
John 45
Mark 35
Explanation: To invoke a static field, we need to use the name of the constructor class. In the above example, we are creating a private static field name by using the keyword static and # for the private field and initializing it to an empty string. Similarly, we are creating a private static field age. Now in order to invoke the above-created fields, we are using the name of the constructor class User as User.#name and User.#age. 
Public Instance Fields: By default, all the properties of a class are public and can be easily accessed outside the class. You can initialize the value of the variable along with the declaration.
Let us look at the example below:
Javascript
<script>class IncrementCounter {     // Public instance field    value = 1;     Increment() {        return this.value++;    }} const counter = new IncrementCounter(); // Accessing a public instance fieldconsole.log(counter.value); // Calling the Increment functioncounter.Increment(); // Printing the updated valueconsole.log(counter.value);</script>
Output:
1
2
Explanation: In the above example, value is declared as a public instance and initialized to 1, so we are easily able to access it using counter.value. There is no restriction on accessing and modifying a public instance field inside the constructor, methods, and also outside the class.
Public static Fields: As we have discussed before the static fields are created by using the static keyword as static staticFieldName. 
Let us look at the example below:
Javascript
<script>class Example {     // Private static field    static value = 42;} // Accessing a public static field using// name of the Constructor classconsole.log(Example.value) console.log(Example.value === 42);</script>
Output:
42
true
Explanation: As you can see we can easily access the public static field outside the class by using the class name.  
sagar0719kumar
akshitsaxenaa09
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.