Getter and Setter in JavaScript
In JavaScript, getters and setters are special methods that allow you to define the behavior of accessing and modifying object properties. They provide a way to control how properties are accessed and updated, allowing you to enforce validation, perform additional actions, or provide computed properties.
Getter and Setter
The JavaScript getter methods are used to access the properties of an object and the Javascript setter methods are used to change the values of an object.
Getters and setters are defined using the get and set keywords within an object literal, a class, or a constructor function. Here's an example that demonstrates the purpose of getters and setters:
For example:
// Using object literal
var person = {
firstName: "John",
lastName: "Doe",
get fullName()
{
return this.firstName + " " + this.lastName;
},
set fullName(value)
{
var parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
console.log(person.fullName); // Output: John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith
In the example above, the person object has a fullName property defined as a getter and a setter :
- The get fullName() method is invoked when accessing the fullName property, and it returns the concatenation of the firstName and lastName properties.
- The set fullName(value) method is invoked when assigning a value to the fullName property, and it splits the value into first and last names, updating the corresponding properties.
You can also use getters and setters in ES6 classes:
class Person
{
constructor(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
get fullName()
{
return this.firstName + " " + this.lastName;
}
set fullName(value)
{
var parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
}
var person = new Person("John", "Doe");
console.log(person.fullName); // Output: John Doe
person.fullName = "Jane Smith";
console.log(person.fullName); // Output: Jane Smith
In this class-based example, we define a Person class with a constructor that initializes the firstName and lastName properties. The fullName property is defined as a getter and a setter, providing the same behavior as in the object literal example.
Conclusion
Getters and setters allow you to add logic and control over property access and modification, giving you more flexibility and encapsulation in your JavaScript objects. Let's read about JavaScript Events in the next section.