Better way of implementing public and private (#) fields in class in js

In JavaScript, getters and setters are special methods that allow you to define how properties of an object are accessed and modified. They provide a way to control access to object properties, allowing you to add logic when getting or setting a value.

  • Getter: A getter is a method that gets the value of a specific property. It is defined using the get keyword.
  • Setter: A setter is a method that sets the value of a specific property. It is defined using the set keyword.

Here’s how you can use getters and setters within a class:

class Circle {
  constructor(radius) {
    this.#radius = radius; // Use # to declare a private property
  }

  // Getter for the radius property
  get radius() {
    return this.#radius;
  }

  // Setter for the radius property
  set radius(value) {
    if (value >= 0) {
      this.#radius = value;
    } else {
      console.error("Radius cannot be negative");
    }
  }

  get area() {
    return Math.PI * this.#radius * this.#radius;
  }
}

const myCircle = new Circle(10);
console.log(myCircle.radius); // Output: 10 (using the getter)

myCircle.radius = 15; // Output: (using the setter)
console.log(myCircle.radius);  // 15

myCircle.radius = -5;    // Error: Radius cannot be negative
console.log(myCircle.radius);  // 15 (the value is not changed)

console.log(myCircle.area); // 706.858 (calculated property)

In this example:

  • We use #radius to store the actual radius value. The # makes it a private property, meaning it can only be accessed from within the Circle class.
  • The get radius() method returns the value of #radius.
  • The set radius(value) method checks if the provided value is valid (non-negative) before updating #radius. If the value is negative, it logs an error.
  • The get area() method calculates the area of the circle. Note that area is a read-only property, as it only has a getter and no setter.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *