Saturday, November 9, 2024

JavaScript Encapsulation Techniques

Objectives:

  • JavaScript encapsulation? 
  • Closures
  • Private Fields in ES2020
  • Modules
JavaScript supports encapsulation, which is a fundamental concept in object-oriented programming. Encapsulation allows an object to protect its internal state and behavior by only exposing a controlled interface. In JavaScript, encapsulation can be achieved in several ways, particularly with the use of closures, ES6 classes with private fields, and modules.

Here are a few ways to implement encapsulation in JavaScript:

1. Using Closures

In JavaScript, closures can be used to create private variables and methods. When you define a function inside another function, the inner function has access to the outer function’s scope, even after the outer function has executed. This allows private data to be encapsulated.

Example

function Person(name) {
    let _name = name;  // private variable

    return {
        getName: function() {  // public method
            return _name;
        },
        setName: function(newName) {  // public method
            _name = newName;
        }
    };
}

const person = Person('Alice');
console.log(person.getName()); // Output: Alice
person.setName('Bob');
console.log(person.getName()); // Output: Bob
console.log(person._name);     // Undefined, _name is private

In this example, _name is a private variable, only accessible through the getName and setName methods, not directly outside the function.

2. Using ES6 Classes with Private Fields

With the introduction of ES2020, JavaScript now supports private fields in classes using the # symbol. These private fields can only be accessed within the class itself.

Example
class Person {
    #name; // private field

    constructor(name) {
        this.#name = name;
    }

    getName() {  // public method
        return this.#name;
    }

    setName(newName) {  // public method
        this.#name = newName;
    }
}

const person = new Person('Alice');
console.log(person.getName()); // Output: Alice
person.setName('Bob');
console.log(person.getName()); // Output: Bob
console.log(person.#name);     // Error, private field '#name' is not accessible
In this example, #name is a private field and can only be accessed within the Person class.

3. Using Modules

JavaScript modules also provide a way to encapsulate variables and functions. When you define functions and variables within a module, only those exported can be accessed from outside the module.

Example (ES6 Modules)
person.js
// Private variable and function are not exported
const _name = 'Alice';
function _privateMethod() {
    return `Hello, ${_name}`;
}

export function publicMethod() {
    return _privateMethod();
}
main.js
import { publicMethod } from './person.js';
console.log(publicMethod());  // Output: Hello, Alice
// Cannot access _name or _privateMethod as they are private

In this example, only publicMethod is exported, so _name and _privateMethod are encapsulated within the module and inaccessible from outside.

Summary

Encapsulation in JavaScript can be achieved through:
  • Closures: By defining private variables within function scopes.
  • Private fields in classes: Using the # syntax.
  • Modules: By exposing only the parts of code you wish to make public.

No comments:

Post a Comment

Hot Topics