Skip to main content

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.

  1. Getter (get):

    • Purpose: The get syntax 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 Person with a private property birthYear. A getter method age could calculate the person's age based on birthYear and the current year.
  2. Setter (set):

    • Purpose: The set syntax 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 Person class, a setter for birthYear could include checks to ensure the year is within reasonable bounds.

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.