Mastering Getter and Setter (Why & How to use them?) πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

JavaScript Getters and Setters

Introduction to Getters and Setters

Getters and setters in JavaScript allow you to control access to object properties. They enable encapsulation by providing a way to define how properties are retrieved and updated.

Getters and Setters in Classes

class Course {
    #name = "Default"; // Private field
 
    constructor(name, teacher, videos) {
        this.#name = name;
        this.teacher = teacher;
        this.videos = videos;
    }
 
    print() {
        console.log(this);
    }
 
    // Getter for the name property
    get name() {
        return this.#name.toUpperCase();
    }
 
    // Setter for the name property
    set name(value) {
        this.#name = value; // Encapsulated logic for setting the name
    }
}
 
const js = new Course("JavaScript", "DeathCode", 40);
js.name = "Advanced JavaScript"; // Using the setter
console.log(js.name); // Using the getter

Explanation:

  • #name: A private field accessible only within the class.
  • get name(): A getter method that returns the name in uppercase.
  • set name(value): A setter method that updates the private field #name.

Getters and Setters in Constructor Functions

function User(name, username) {
    this._name = name; // Internal property
    this._username = username;
 
    Object.defineProperty(this, 'name', {
        get: function () {
            return this._name.toUpperCase();
        },
        set: function (value) {
            this._name = value; // Encapsulated logic for setting the name
        }
    });
}
 
const user = new User("death", "deathcode");
console.log(user.name); // Using the getter
user.name = "newName"; // Using the setter
console.log(user.name);

Explanation:

  • Object.defineProperty: Used to define getters and setters on object properties.
  • get: Retrieves the value of the property with additional logic.
  • set: Updates the property value with additional logic.

Behind the Scenes: How Getters and Setters Work

In classes, getters and setters are syntactic sugar over the Object.defineProperty mechanism. When you define a getter or setter, the property is automatically added to the object's prototype.

Key Features and Benefits

  • Encapsulation: Control how properties are accessed and modified.
  • Validation: Add custom logic for property updates.
  • Readability: Provide intuitive interfaces for object properties.

Best Practices

  • Use getters and setters for encapsulation and validation.
  • Avoid excessive logic in getters and setters to maintain performance.
  • Prefer private fields (e.g., #name) for truly private data in classes.
Β© 2024 DeathCode. All Rights Reserved.