
Understanding Getters, Setters, and Class Fields in JavaScript
JavaScript is a versatile language that continues to evolve, introducing new features that make it easier to write clean and maintainable code. Among these features are getters, setters, and class fields (both public and private). These concepts are essential for managing object properties and encapsulating data within classes. In this article, we’ll explore these concepts with examples to help you understand how to use them effectively.
1. Getters and Setters in JavaScript Classes
Getters and setters are special methods in JavaScript that allow you to define how a property is accessed (get
) or modified (set
). They are particularly useful when you want to add logic or validation when retrieving or setting a value.
Example: Basic Getter and Setter
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter for fullName
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// Setter for fullName
set fullName(name) {
const [firstName, lastName] = name.split(' ');
this.firstName = firstName;
this.lastName = lastName;
}
}
const person = new Person('John', 'Doe');
console.log(person.fullName); // Output: John Doe
person.fullName = 'Jane Smith';
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith
In this example:
- The
get fullName()
method retrieves the full name by combiningfirstName
andlastName
. - The
set fullName(name)
method splits the input string and assigns the values tofirstName
andlastName
.
2. Combining Getters and Setters
Getters and setters can be combined to create more robust and controlled access to properties. This is especially useful when you want to enforce rules or perform calculations when accessing or modifying a property.
Example: Combining Getters and Setters
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
// Getter for area
get area() {
return this.width * this.height;
}
// Setter for area (updates width and height proportionally)
set area(value) {
const ratio = this.width / this.height;
this.height = Math.sqrt(value / ratio);
this.width = ratio * this.height;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // Output: 50
rect.area = 100;
console.log(rect.width); // Output: 14.142135623730951
console.log(rect.height); // Output: 7.0710678118654755
Here:
- The
get area()
method calculates the area of the rectangle. - The
set area(value)
method updates the width and height proportionally based on the new area.
3. Class Fields: Public and Private
Class fields allow you to define properties directly within a class. JavaScript supports both public and private fields. Public fields are accessible outside the class, while private fields are only accessible within the class.
Example: Public and Private Fields
class User {
// Public field
name = 'Anonymous';
// Private field
#age = 0;
// Getter for age
get age() {
return this.#age;
}
// Setter for age
set age(value) {
if (value < 0) {
throw new Error('Age cannot be negative');
}
this.#age = value;
}
}
const user = new User();
console.log(user.name); // Output: Anonymous
console.log(user.age); // Output: 0
user.age = 25;
console.log(user.age); // Output: 25
// Uncommenting the following lines will throw an error
// console.log(user.#age); // SyntaxError: Private field '#age' must be declared in an enclosing class
In this example:
name
is a public field that can be accessed directly.#age
is a private field that can only be accessed or modified through theget age()
andset age()
methods.
4. Getters with Private Fields
Getters are particularly useful when working with private fields, as they provide controlled access to private data.
Example: Getters with Private Fields
class BankAccount {
// Private field
#balance = 0;
// Getter for balance
get balance() {
return this.#balance;
}
// Method to deposit money
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.balance); // Output: 100
// Uncommenting the following line will throw an error
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
Here:
- The
#balance
field is private and cannot be accessed directly. - The
get balance()
method provides read-only access to the balance.
5. Setters with Private Fields
Setters are equally important when working with private fields, as they allow you to enforce rules or validation when modifying the private data.
Example: Setters with Private Fields
class Car {
#mileage = 0;
set mileage(value) {
if (value < 0) {
throw new Error('Mileage cannot be negative.');
}
this.#mileage = value;
}
get mileage() {
return this.#mileage;
}
}
const myCar = new Car();
myCar.mileage = 5000;
console.log(myCar.mileage); // Outputs: 5000
In this example:
- The
#mileage
field is private and can only be accessed or modified directly. - The
get mileage()
andset mileage()
methods provide access to the private field.
Conclusion
Getters, setters, and class fields are powerful tools in JavaScript that help you manage object properties and encapsulate data effectively. By using these features, you can write cleaner, more maintainable, and more robust code. Whether you’re working with public or private fields, getters and setters provide a controlled way to access and modify data, ensuring that your objects remain consistent and valid.
By mastering these features, you can write more secure and maintainable JavaScript code. Whether you’re working on large applications or small projects, these tools will help you implement complex logic with ease and precision.