classes-get-set
In JavaScript, get and set are special types of methods within a class that are used to define accessors and mutators for properties. Their primary purpose is to provide a way to get and set the values of private properties in a controlled manner.
Getter (
get):- Purpose: The
getsyntax binds an object property to a function that will be called when that property is looked up. It's used to return the internal property's value. - Usage: This is particularly useful when you want to perform some action on the data while retrieving it, such as formatting a date or returning a computed value.
- Example: Imagine a class
Personwith a private propertybirthYear. A getter methodagecould calculate the person's age based onbirthYearand the current year.
- Purpose: The
Setter (
set):- Purpose: The
setsyntax binds an object property to a function to be called when there is an attempt to set that property. It allows you to control how the value of the property can be set. - Usage: Setters are useful for validating input or performing some calculations before setting a property. For instance, you might want to ensure a given input is of a certain format or within a range before setting the property value.
- Example: In the
Personclass, a setter forbirthYearcould include checks to ensure the year is within reasonable bounds.
- Purpose: The
Using getters and setters can lead to better data encapsulation and abstraction. They allow an object to manage its internal state and expose a controlled interface to the outside world. This is a key principle in object-oriented programming, helping to maintain the integrity of the data within objects and making the code more robust and maintainable.