JavaScript Object Get / Set
Getters and setters allow defining custom logic for reading and writing object properties. They can compute values on the fly or validate incoming data.
Key Topics
Defining Getters and Setters
Use get
and set
in object literals or Object.defineProperty()
to control how properties are accessed or assigned.
let user = {
_firstName: "Alice",
_lastName: "Smith",
get fullName() {
return this._firstName + " " + this._lastName;
},
set fullName(value) {
[this._firstName, this._lastName] = value.split(" ");
}
};
console.log(user.fullName);
user.fullName = "Bob Jones";
console.log(user._firstName);
Output
> Alice Smith
> Bob
Explanation: Reading user.fullName
calls the getter, returning a computed string. Setting it splits the string and updates both _firstName
and _lastName
.
Computed Values
Getters can return dynamic or combined property values without storing them in memory. This is handy for automatic calculations or transformations.
Validation Logic
Setters can validate data (e.g., limit length, enforce formats) before storing it, ensuring the object remains in a valid state.
JavaScript Usage in DOM
Below is a complete DOM example showing how a setter automatically updates an element when a property changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Getters/Setters in DOM</title>
</head>
<body>
<h1>Object Get/Set Demo</h1>
<p>Type a value and update the object property:</p>
<input type="text" id="inputVal" placeholder="Enter name">
<button onclick="updateUser()">Set Full Name</button>
<p id="output"></p>
<script>
let personState = {
_first: "",
_last: "",
get fullName() {
return this._first + " " + this._last;
},
set fullName(val) {
[this._first, this._last] = val.split(" ");
document.getElementById("output").textContent = "Full Name: " + this.fullName;
}
};
function updateUser() {
let val = document.getElementById("inputVal").value;
personState.fullName = val;
}
</script>
</body>
</html>
Key Takeaways
- Define Accessors:
get
andset
manage property logic. - Computed Values: Generate dynamic data on reads.
- Validation: Check or transform data in setters before assignment.
- DOM Integration: Tie property changes to automatic UI updates.