In languages such as Java and C++, you can declare and initialize variables, also known as fields or attributes, within the class body.
In JavaScript, the most common way to declare fields is within the class constructor:
This approach is beneficial when you want to allow clients to instantiate a class with custom values for initializing the fields:
Alternatively, you can initialize the fields in the class body:
However, for improved readability, it’s advisable to always initialize your class attributes within the constructor.
Fields with Default Values
You can initialize a field and use the constructor to override its initial value. Here’s an example:
You can also use parameters with default values to achieve the same result:
Declaring Fields Inside Methods
You are not restricted to declaring fields only within the constructor or class body. They can be declared within any method.
Though assigning properties within any method is possible, it’s generally not recommended. It could lead to unpredictable class structures and make the code more challenging to understand.
Information Hiding
Private fields can be declared using a hash # prefix. They can only be accessed from within the class that defines them:
Here, #balance is a private field. It can’t be accessed from outside the Account class. Attempting to access #balance outside of class methods will result in a syntax error. This is beneficial for encapsulation, where a class’s internal details are hidden from the external world.
Declaring Methods
Methods can be declared in the class body or within the constructor. Here’s an example of declaring a method in the class body:
In this example, deposit, withdraw, and print are methods of the Account class. They can be invoked on an instance of the Account class:
You can also declare methods within the constructor:
In this example, deposit, withdraw, and print are declared within the constructor. They can be invoked in the same way as the previous example. In a situation like this, you can make clever use of closures to create private methods or fields. Here is an example where balance is a private field:
You can also use arrow functions to declare methods (inside the constructor or class body):
Methods can be declared pretty much anywhere in a class. However, it’s recommended to declare them in the class body for better readability and maintainability. Moreover, you can make any of the methods private by using the # prefix. This way, the method can only be accessed from within the class that defines it.