Menü schliessen
Created: December 9th 2021
Last updated: March 4th 2022
Categories: JavaScript Development
Author: Tim Fürer

JavaScript: Create an Extendable Module

Tags:  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Creating an extendable module in JavaScript is easy. In this guide, I'll show you how to do it.

The approach I'll use is similar to jQuery's and gives you control over which parts of the module are left exposed.


Module Wrapper

First, we'll create a wrapper. Essentially, it's an anonymous function that exposes chosen contents to the window object. We'll use the block scope to our advantage to have contents inside the function that remain exclusive to it.

This is the basic setup I like to use:

(function(window) {
    // Module Contents
})(typeof window !== 'undefined' ? window : this);

As you might see, we find and pass the correct window object as a parameter to the function. This is simply for better compatibility and isn't necessary.

If you know for sure that you have access to the window, you can also use this:

(function() {
    // Module Contents
})();

Module Contents And Exposing Them

Onto the module's contents. Let's have a function that alerts a secret value.

(function(window) {
    const secret = 42;

    const reveal = function() {
        alert(secret);
    };
})(typeof window !== 'undefined' ? window : this);

That'll do. Now, let's expose our "reveal" function:

(function(window) {
    const secret = 42;

    const reveal = function() {
        alert(secret);
    };

    window[reveal] = reveal;
})(typeof window !== 'undefined' ? window : this);

What we've done here is we've created a new variable inside the window object from our existing module variable, the function. Window variables are global, thus, exposed.

We can now access and execute our exposed function like this:

reveal()

It'll alert our secret value, which is "42". This is interesting because, while the function can access the secret value, the user cannot.


Module Extension

Extending a module is just as easy as creating one.

Use the following setup:

(function(modulePart) {
    // Extension Content
})(modulePart);

We pass the exposed module part that is to be extended as a parameter to an anonymous function that then modifies or does something with it.