Tutorials  /  JavaScript

JavaScript Module Design Pattern: Structuring Your Code

Ccentron Redaktion · November 2023 ·3 min read ·JavaScript, Tutorial

The module design pattern in JavaScript allows you to divide your code into independent parts, promoting well-structured code. We'll show you how it works.

In the world of JavaScript programming, modules are the order of the day when it comes to keeping parts of your code independent of other components. This promotes loose coupling and ensures well-structured code.

For those familiar with object-oriented programming languages, modules are akin to "classes" in JavaScript. One of the many benefits of classes is called "encapsulation," which involves protecting states and behaviors from access by other classes. The module pattern enables both public and private access levels.

Modules should be created as "Immediately-Invoked Function Expressions" (IIFE) to enable private scopes. This means that variables and methods are protected, and an object is returned instead of a function. Here's an example:

Code
(function() {
    // Declare private variables and/or functions
    return {
        // Declare public variables and/or functions
    }
})();

In this example, private variables and/or functions are declared first before returning the object. Code outside of our closure cannot access these private variables since it's not in the same scope.

Let's illustrate this with a concrete implementation:

JavaScript
var HTMLChanger = (function() {
    var contents = 'Contents';

    var changeHTML = function() {
        var element = document.getElementById('attribute-to-change');
        element.innerHTML = contents;
    }

    return {
        callChangeHTML: function() {
            changeHTML();
            console.log(contents);
        }
    };
})();

HTMLChanger.callChangeHTML();       // Outputs: 'Contents'
console.log(HTMLChanger.contents);  // undefined

Note that `callChangeHTML` is bound to the returned object and can be referenced within the HTMLChanger namespace. However, you cannot access `contents` outside of the module.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Revealing Module Pattern

A variation of the module pattern is known as the "Revealing Module Pattern." Its purpose is to maintain encapsulation while exposing specific variables and methods returned within an object literal. The direct implementation looks like this:

JavaScript
var Exposer = (function() {
    var privateVariable = 10;

    var privateMethod = function() {
        console.log('Inside a private method!');
        privateVariable++;
    }

    var methodToExpose = function() {
        console.log('This is a method I want to expose!');
    }

    var otherMethodIWantToExpose = function() {
        privateMethod();
    }

    return {
        first: methodToExpose,
        second: otherMethodIWantToExpose
    };
})();

Exposer.first();        // Output: This is a method I want to expose!
Exposer.second();       // Output: Inside a private method!
Exposer.methodToExpose; // undefined

While this looks cleaner, an obvious drawback is that private methods cannot be accessed. This can pose challenges in unit testing. Similarly, the public behaviors are not overridable.

Overall, JavaScript modules and the Revealing Module Pattern provide a powerful way to organize and protect your code. Choose the model that best suits your requirements and benefit from better-structured and maintainable code. MongoDB Security Best Practices for Network Access Control Explained with Examples

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren