How to Use Public Instance Getter Setter in JavaScript

A public instance getter setter is a pair of special methods that allow you to get and set the value of a property of an object or a class instance. A getter setter is defined using the get and set keywords before the method name, and it takes one parameter for the setter. A getter setter can be used to perform some computation, validation, or side effects before getting or setting the property value, or to create a read-write property.

Why use public instance getter setter?

Public instance getter setter are useful for the following reasons:

  • They provide a way to encapsulate the internal state of an object or a class instance, and expose only the necessary information to the outside world.
  • They allow you to define custom logic for getting and setting a property, such as checking for errors, caching results, logging actions, or triggering events.
  • They make the code more readable and consistent, as you can use the dot notation (obj.prop) to get and set a property, instead of calling different methods (obj.getProp() and obj.setProp()).

How to define public instance getter setter?

You can define a public instance getter setter using the following syntax:

Javascript
                        
class ClassName {
  // define a property
  prop = "some value";

  // define a getter for the property
  get prop() {
    // getter body
    return this.prop;
  }

  // define a setter for the property
  set prop(value) {
    // setter body
    this.prop = value;
  }
}

You can access a public instance getter setter using the dot notation (instance.prop), as if it was a regular property. The getter will be invoked automatically when you get the property, and it will return the value of the property. The setter will be invoked automatically when you set the property, and it will assign the value to the property.

Note: You can define a getter without a setter, or a setter without a getter, but it is not recommended, as it may cause confusion and inconsistency. If you want to define a read-only property, use a getter only. If you want to define a write-only property, use a setter only.

Example of public instance getter setter

Let's see an example of how to use a public instance getter setter in a class. Suppose you have a class called Counter, which represents a simple counter that can be incremented or decremented. You want to define a getter setter for the value of the counter, which is initialized to zero. The getter setter should check if the value is within a certain range, and emit an event if the value changes.

Javascript
                        
class Counter {
  // define a constructor method
  constructor() {
    // initialize the value to zero
    this._value = 0;
    // create an event emitter
    this._emitter = new EventTarget();
  }

  // define a getter for the value
  get value() {
    // return the value
    return this._value;
  }

  // define a setter for the value
  set value(newValue) {
    // validate the new value
    if (typeof newValue !== "number") {
      throw new TypeError("The value must be a number");
    }
    if (newValue < 0 || newValue > 10) {
      throw new RangeError("The value must be between 0 and 10");
    }
    // check if the value has changed
    if (newValue !== this._value) {
      // assign the new value
      this._value = newValue;
      // emit an event
      this._emitter.dispatchEvent(new CustomEvent("valueChanged", {
        detail: {
          value: this._value
        }
      }));
    }
  }

  // define a method to increment the value
  increment() {
    // set the value to the current value plus one
    this.value = this.value + 1;
  }

  // define a method to decrement the value
  decrement() {
    // set the value to the current value minus one
    this.value = this.value - 1;
  }

  // define a method to add a listener for the value changed event
  onValueChanged(listener) {
    // add the listener to the event emitter
    this._emitter.addEventListener("valueChanged", listener);
  }
}

// create a new instance of the class
const counter = new Counter();

// add a listener for the value changed event
counter.onValueChanged(event => {
  // log the new value
  console.log(`The value is now ${event.detail.value}`);
});

// get the value
console.log(counter.value); // 0

// set the value
counter.value = 5; // The value is now 5

// increment the value
counter.increment(); // The value is now 6

// decrement the value
counter.decrement(); // The value is now 5

In this example, you can see that the getter setter for the value is defined using the get and set keywords and the name of the property. The getter returns the value of the _value property, which is prefixed with an underscore to indicate that it is a private property. The setter takes a parameter for the new value, and validates it using the typeof and if statements. The setter also checks if the new value is different from the current value, and if so, assigns it to the _value property and emits a custom event using the EventTarget and CustomEvent objects. You can access the getter setter using the dot notation (counter.value), and it will get or set the value of the counter. You can also use the increment and decrement methods to change the value by one, and the onValueChanged method to add a listener for the value changed event.

Conclusion

In this article, you learned about public instance getter setter in JavaScript, which are pairs of methods that allow you to get and set the value of a property of an object or a class instance. You learned how to define a getter setter using the get and set keywords, and how to access it using the dot notation. You also learned the benefits of using getter setter, such as encapsulating the internal state, defining custom logic, and making the code more readable and consistent.