Зміст курсу
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Getters and Setters
Getters and setters provide a powerful way to control access to an object's properties in JavaScript.
What Are Getters and Setters?
In JavaScript, getters and setters are special methods that allow controlled access to an object's properties. They give you the flexibility to define how a property is retrieved and modified while protecting the object's internal state.
- Getter: A method used to retrieve (get) the value of a property;
- Setter: A method used to set or update the value of a property.
Think of a bank vault. The vault holds valuable items (private properties), and the bank teller (getter/setter) acts as the gatekeeper. You can't access the vault directly, but the teller can retrieve or update items for you based on certain rules and validations.
How to Define and Use Getters and Setters
Getters and setters are defined using the get
and set
keywords inside a class. When you access a property, the getter is automatically invoked. Similarly, when you modify a property, the setter is called instead of directly modifying the property.
class Animal { #type; // Private field constructor(name, type) { this.name = name; this.#type = type; // Assigning the private field } // Getter for the type property get type() { return this.#type; } // Setter for the type property set type(newType) { if (newType) { this.#type = newType; } else { console.log('Invalid type'); } } } const lion = new Animal('Lion', 'Wild'); // Using getter to access the private type console.log(lion.type); // Output: Wild // Using setter to modify the private type lion.type = 'Domestic'; console.log(lion.type); // Output: Domestic // Trying to set an invalid value lion.type = ''; // Output: Invalid type
In this example, #type
is a private property, and we define a getter (get type()
) to retrieve its value and a setter (set type(newType)
) to modify it. The setter includes validation to prevent setting an invalid value, demonstrating how you can control updates to private data.
Benefits of Getters and Setters
Controlled Access
- Getters let you define how a property's value is accessed, enabling you to process or manipulate the value before returning it;
- Setters give you control over how a property is updated, allowing you to validate or transform the data before assigning it to a private field.
Data Protection
- Using getters and setters helps safeguard the internal state of an object by providing a controlled interface for interaction;
- Private properties can remain hidden, and you can expose only the necessary information to external code.
Flexibility
Getters and setters allow you to add additional logic—like validation or logging—when accessing or modifying properties without altering how external code interacts with the object.
Example: User Account with Password Validation
Imagine you are managing user accounts where passwords need to meet certain security standards. Using a setter, you can enforce password strength, while a getter could retrieve a masked version of the password for display purposes.
class UserAccount { #password; // Private field constructor(username, password) { this.username = username; this.#password = password; } // Getter for password (returning a masked version) get password() { return '*'.repeat(this.#password.length); // Mask the password when retrieved } // Setter for password with validation set password(newPassword) { if (newPassword.length >= 8) { this.#password = newPassword; } else { console.log('Password must be at least 8 characters long'); } } } const user = new UserAccount('nick_feather', 'secret123'); // Accessing the password using the getter (masked) console.log(user.password); // Output: ********* // Setting a new valid password using the setter user.password = 'strongPassword123'; console.log(user.password); // Output: *************** // Trying to set an invalid password user.password = '123'; // Output: Password must be at least 8 characters long
In this example, the getter returns a masked version of the password to hide the actual value, and the setter enforces password validation, ensuring the password is at least 8 characters long.
Example with Validation Logic Using Getters and Setters
Here's another example where we manage a person's age and ensure that the value stays within a reasonable range:
class Person { #age; // Private field constructor(name, age) { this.name = name; this.#age = age; } // Getter for age get age() { return this.#age; } // Setter for age with validation set age(newAge) { if (newAge > 0 && newAge < 120) { this.#age = newAge; } else { console.log('Invalid age'); } } } const peter = new Person('Peter', 30); // Accessing the age using the getter console.log(peter.age); // Output: 30 // Setting a new valid age using the setter peter.age = 35; console.log(peter.age); // Output: 35 // Trying to set an invalid age peter.age = 150; // Output: Invalid age
This example demonstrates how a setter can ensure that an age remains within a valid range, preventing invalid data from being stored.
Дякуємо за ваш відгук!