Last active
February 10, 2020 18:42
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
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