Getters & Setters Flashcards
Why are getters useful?
If we have an object which contains a mutable property, we can use a getter to allow access to that property without risking the user mutating the data unintentionally.
How do you define a getter?
get students() {
return […this._students]; // A copy of the _students array
},
What is the syntax of a setter?
a setter looks like a concise syntax method definition preceded by the keywordset
Why can there be a risk of stack overflow with getter?
if the getter has the same name as the thing you are trying to get, you can end up in a recursive loop as the getter ends up calling itself each time it runs.
What do setters take?
A setter takes a single argument: the value you want to assign to the property.
How do you use getters and setters?
you use setters & getters just like ordinary properties, not methods. In other words, you writestudent.firstName = something,notstudent.firstName(something). or just student.firstName