Exploring Code #63: Getters & Setters in JS Classes
What are getters and setters in JS classes?
Really, they aren't that complex.
So, why not start with Getters.
Getters
Let's say you have a class called FastFood.
And you want to define a method that spits out best combo at whatever fast food place you instantiate.
class FastFood {
constructor(name, goToMealNumber) {
this.name = name;
this.goToMealNumber = goToMealNumber;
}
get bestCombo() {
return `The best combo at ${this.name} is the #${this.goToMealNumber}.`
}
}
const mcdonalds = new FastFood('mcdonalds', 2)
So, just picking a random combo number at Mcdonalds. We get the following output.
The get keyword before bestCombo that portion of the class into a property + the functionality of a function.
get bestCombo() {
return `The best combo at ${this.name} is the #${this.goToMealNumber}.`
}
Looks like a function. Tastes like a function. Smells like a function. But I'm not actually invoking it within the console when I run that method.
Kinda weird.
But really, the whole point of the getter is just to return a value. It's not meant to actually return a function that can be used with variable arguments.
领英推荐
It's also a good way to indicate in your code to other developers (and your future self) that the method inside of the class has a specific purpose for getting a value; that the function is immediately invoked upon instantiation and essentially that block is just a property that is attached to the class - nothing more.
That's all.
Setters
Very similar to getters, but instead we are actively setting a property inside of the class.
So, take the same FastFood class and modify it a bit - removing the getter for simplicity, as well as the property names to use underscores to avoid an infinite recursion:
class FastFood {
constructor(name) {
this._name = name;
this._comboNumber = 2;
}
set comboNumber(num) {
if (num < 0) {
throw new Error("Number cannot be negative");
}
else {
this._comboNumber = num;
}
}
}
const mcdonalds = new FastFood('mcdonalds', 2)
mcdonalds._comboNumber = 4;
And you can now set the _comboNumber property, but with extra logic that operates with basic error handling (checking for negative number).
And add a negative number in there:
And there you go.
Obviously, the use-case for getters and setters will be more complex on production-ready applications, but you can see the value here in the concept.
And they are a gateway into JS proxies, which are the more modern way of going about this sort of thing.
I'll write about those eventually.