Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript Module Pattern that returns a function (instead of an object) which contains other functions...
{
let Module = (function() {
let privateMethod1 = function() {
console.log("FOO");
};
let privateMethod2 = function() {
console.log("BAR");
};
let privateMethod3 = function() {
console.log("TEA");
};
let constructor = function(msg) {
console.log(msg);
};
return Object.assign(constructor, {
publicMethod1: privateMethod1,
publicMethod2: privateMethod2,
});
})();
Module.extension1 = function(msg) {
this(msg); // prints passed argument string (i.e 'Hello goodbye')
this.publicMethod1(); // prints 'FOO'
this.publicMethod2(); // prints 'BAR'
this.privateMethod3(); // Not exposed, so results in -> Uncaught TypeError: Module.privateMethod3 is not a function ...
};
Module('Hello world'); // prints 'Hello world'
Module.publicMethod1(); // prints 'FOO'
Module.publicMethod2(); // prints 'BAR'
Module.extension1('Hello goodbye'); // prints 'Hello goodbye', 'FOO' and 'BAR'
Module.privateMethod3(); // Not exposed, so results in -> Uncaught TypeError: Module.privateMethod3 is not a function ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment