Javascript setters
Created By: chatGPT
Setters in JavaScript provide a way to execute a function when a property is set on an object. They are defined using the
set
keyword within an object literal or class. This allows you to define custom behavior when values are assigned to properties, which can be extremely beneficial for validation or triggering other actions during property assignment.const person = {
firstName: '',
lastName: '',
fullName: '',
set firstName(value) {
this._firstName = value;
this.updateFullName();
},
set lastName(value) {
this._lastName = value;
this.updateFullName();
},
updateFullName() {
this.fullName = `${this._firstName} ${this._lastName}`;
}
};
person.firstName = 'John';
person.lastName = 'Doe';
console.log(person.fullName); // John Doe
In this example, we have an object
person
with private properties _firstName
and _lastName
. The setters for firstName
and lastName
automatically update the fullName
whenever these properties are modified. This demonstrates how you can encapsulate and manage state effectively.console.log(person.firstName); // John
console.log(person.lastName); // Doe
You can also create setters within a class structure. This provides the same capabilities of encapsulation and custom behavior, but within the context of object-oriented programming.
class Person {
constructor() {
this._firstName = '';
this._lastName = '';
}
set firstName(value) {
this._firstName = value;
this.updateFullName();
}
set lastName(value) {
this._lastName = value;
this.updateFullName();
}
updateFullName() {
this.fullName = `${this._firstName} ${this._lastName}`;
}
}
const person = new Person();
person.firstName = 'Jane';
person.lastName = 'Smith';
console.log(person.fullName); // Jane Smith
Using setters improves the maintainability of your code, as it centralizes property management logic, ensuring that all necessary updates or validations happen automatically whenever a property is modified. This creates a more robust and less error-prone codebase, while also making the code clearer and more intuitive.
console.log(person.firstName); // Jane
console.log(person.lastName); // Smith