Skip to content Skip to sidebar Skip to footer

Adding Methods To Javascript Module Pattern

Just learned about JavaScript module pattern. Love it! So, I created my generic custom library which is located in one file which I include on all my projects. I then want to add

Solution 1:

You can add a property or function by just saying Module.namedproperty = ...whatever...

But it should be noted that if this is in a different file it won't have access to any private variables in the module state.

If you want to have additional private state for these new methods, or want to not worry about which file is run first you can set up your modules like this

varMODULE = (function (my) {
    var privateVariable = 1;

    functionprivateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}(MODULE||{}));

Which will create a new module if the module hasn't been created yet, or add to the existing one if it has.

The private variables will still be private to their own particular closure though, and not to the namespace/module as a whole.

Update to explain

This module format takes in an input into its closure function. If MODULE is already defined, it takes in the MODULE object, otherwise it creates a new empty object. || is logical OR, so MODULE||{} is the same as "if MODULE is defined and is truthy (which an object like MODULE will be), then pass it, if it is undefined or otherwise falsy, pass an empty object.

The extra parentheses are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself.

Post a Comment for "Adding Methods To Javascript Module Pattern"