Getters and Setters in Classes
You'll learn how to use the same get and set syntax inside class definitions to create accessor properties on every instance automatically.
The Core Idea
Everything you learned about getters and setters in object literals works exactly the same way in classes. The difference? When you define get or set methods in a class, every instance created from that class gets those accessor properties automatically. It's like building the getters and setters into your blueprint rather than hand-coding them for each object.
How It Works
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get fahrenheit() {
return (this._celsius * 9/5) + 32;
}
set fahrenheit(value) {
this._celsius = (value - 32) * 5/9;
}
}
const temp = new Temperature(0);
console.log(temp.fahrenheit); // 32 (getter called)
temp.fahrenheit = 68; // setter called
console.log(temp._celsius); // 20
Notice how you use temp.fahrenheit just like a property, not temp.fahrenheit(). The class syntax creates these accessors on every instance you make.
Why Use This?
Classes naturally organize validation and computed properties. You define the logic once in the class, and all instances inherit that behavior. It keeps your code DRY (Don't Repeat Yourself) and makes validation or computation automatic for every object.
Key Takeaway: Using get and set in class definitions creates accessor properties on all instances, applying the same property-like syntax you've already learned to a reusable class template.