Could we help you? Please click the banners. We are young and desperately need the money
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.
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
})();
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.
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.