Skip to content

Instantly share code, notes, and snippets.

@manciuszz
Last active February 10, 2020 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manciuszz/f9299ca0deff5539cb5c5490023934db to your computer and use it in GitHub Desktop.
Save manciuszz/f9299ca0deff5539cb5c5490023934db to your computer and use it in GitHub Desktop.
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