JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Object Accessors

In JavaScript, object accessors provide a way to intercept accesses to object properties using getter and setter methods. These methods allow you to control how values are set and retrieved, enhancing functionality such as input validation, setting properties based on other properties, and even computation based on other data within the object.

Why Use Accessors?

Accessors are particularly useful because they offer an encapsulated approach to managing data within objects. With getters and setters, you can:

  • Control how important values are added or modified.
  • Validate data before it’s stored.
  • Compute derived values dynamically.

Getters in JavaScript

Getters are functions that get the values of variables. The getter method returns the value of the variable. It is defined using the get keyword.

Syntax

Getters are methods that get the value of an internal property. They do not take any arguments and are used to return the internal state of an object.

Javascript
Javascript
. . . .

Explanation:

  • let obj = {} defines an object literal.
  • _propertyName: 'value' is a property that is intended to be private. It holds the value that will be accessed by the getter.
  • get propertyName() {} defines a getter method. When you access obj.propertyName, this method is automatically called.
  • return this._propertyName; inside the getter method returns the value of _propertyName.
  • let val = obj.propertyName; demonstrates using the getter.

Setters in JavaScript

Setters are methods used to set the value of an internal property. They take one argument which is the new value to be set, and they are used to control how values are changed within an object.

Syntax

Javascript
Javascript
. . . .

Explanation

  • set propertyName(value) {} defines a setter method. When obj.propertyName is set to a new value, this method is automatically called.
  • this._propertyName = value; inside the setter method sets the internal property _propertyName to the new value passed to the setter.
  • obj.propertyName = 'new value'; demonstrates using the setter. Setting propertyName triggers the setter method, which updates _propertyName to 'new value'.

Example: Basic Use of Getters and Setters in an Object Literal

In this simple example, we'll create an object using an object literal that includes a getter and a setter for managing a single property. This demonstrates the basic functionality of encapsulating access to a property of an object.

Javascript
Javascript

. . . .

Explanation:

  1. Initialize Private Property:

    • _name is initialized as 'John Doe'. This property is prefixed with an underscore to indicate that it is intended for private use and should not be accessed directly outside of the object's methods.
  2. Define Getter and Setter for name:

    • get name(): This getter allows external code to access the value of _name safely. It simply returns the _name property, enabling read access without directly exposing the private variable.
    • set name(value): The setter provides a safe way to modify _name. It takes a new value and assigns it to _name, encapsulating the logic for updating the property within the setter method.
  3. Using the Object's Property:

    • The name property is accessed using its getter, which returns the initial value "John Doe".
    • The name property is then updated using the setter to "Jane Doe", demonstrating how the setter method can be used to change the property's value.
    • The updated name property is accessed again to confirm that the setter has modified the internal state as expected.

Getters and Setters with Classes in JavaScript

In JavaScript, using getters and setters within classes is a powerful way to control access to an object's properties. These methods allow you to define custom logic for reading and writing values, enhancing encapsulation and data integrity. This approach is particularly useful for validating data, handling side effects, or computing derived properties dynamically.

Example: Simple Accessors in a Class

The below example creates a class that manages a single property name with a getter and a setter to illustrate basic data encapsulation.

Javascript
Javascript

. . . .

Explanation:

  • Class Definition and Constructor: The Person class is defined with a single private property _name, which is initialized through the constructor. The underscore (_) prefix is a convention to suggest that _name should not be accessed directly outside of class methods.
  • Getter for name: The get name() method provides read access to the _name property. When person.name is accessed, this getter is invoked to return the current value of _name.
  • Setter for name: The set name(value) method allows controlled modification of the _name property. When person.name is assigned a new value, this setter is called, updating _name with that new value.
  • Using the Class: An instance of the Person class is created with the name "John". The name is accessed and printed using the getter, then changed using the setter, and printed again to reflect the update.

Why Use Getters/Setters Over Methods?

Using getters and setters instead of regular methods offers several advantages:

  • Semantic Clarity: Accessors allow properties to be accessed like regular properties, which is syntactically clearer than method calls.
  • Encapsulation: They help in encapsulating the internal representation and can validate or compute values on-the-fly without external intervention.
  • Interoperability: When using libraries or frameworks that expect properties to be accessed directly, accessors can intercept these accesses and provide custom logic without altering the consuming code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next