In JavaScript, getters and setters are special functions that allow you to control access to an object’s properties. They provide a way to encapsulate the internal state of an object, allowing you to add logic when getting or setting values. Here’s a guide on how to use getters and setters in JavaScript:
Start by creating a basic JavaScript object. In this example, we’ll create a Person
object with name
and age
properties.
const person = {
name: 'John Doe',
age: 25,
};
Use the Object.defineProperty
method to add getters and setters to your object.
Object.defineProperty(person, 'fullName', {
get: function() {
return this.name;
},
});
Now, when you access person.fullName
, it will return the value of person.name
Object.defineProperty(person, 'fullName', {
get: function() {
return this.name;
},
set: function(value) {
const [firstName, lastName] = value.split(' ');
this.name = firstName;
this.lastName = lastName;
},
});
Now, when you set person.fullName
, it will split the value into first and last names and update the name
and lastName
properties.
Now that you’ve added getters and setters, you can interact with your object as follows:
// Using the getter
console.log(person.fullName); // Output: John Doe
// Using the setter
person.fullName = 'Alice Wonderland';
console.log(person.name); // Output: Alice
console.log(person.lastName); // Output: Wonderland
With the introduction of ES6 classes, you can also use the get
and set
keywords directly within a class definition.
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
// Getter
get fullName() {
return this._name;
}
// Setter
set fullName(value) {
const [firstName, lastName] = value.split(' ');
this._name = firstName;
this._lastName = lastName;
}
}
_name
) to indicate that they should not be accessed directly.At ceawebsystems, our commitment to trust, security, and quality extends beyond the finished products we deliver to our clients. As a forward-thinking software development company, we recognize the importance of adopting modern technologies and frameworks to ensure our solutions align seamlessly with the dynamic needs of our client