Last active
October 22, 2020 08:32
-
-
Save archan937/06d571113daa6898fb5225d98b08405d to your computer and use it in GitHub Desktop.
Javascript Module Pattern
This file contains hidden or 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
const MyCoolModule = (() => { | |
let | |
privateState = {}, | |
privateVariable = 'private', | |
bothPrivateAndPublicVariable = 'private and public', | |
init = () => { | |
// do some initialization stuff | |
console.log('Initialized MyCoolModule!'); | |
}, | |
privateFunctionA = (k, v) => { | |
privateState[k] = v; | |
console.log('private state', privateState); | |
}, | |
privateFunctionB = (arg) => { | |
// do something | |
}; | |
init(); | |
return { | |
publicVariable: 'public', | |
publicFunction: privateFunctionA, // private function made public | |
bothPrivateAndPublicVariable, | |
}; | |
})(); | |
//=> 'Initialized MyCoolModule!' in console on page load | |
MyCoolModule.publicVariable; //=> 'public' | |
MyCoolModule.publicFunction('a', 1); //=> 'private state {a: 1}' in console | |
MyCoolModule.publicFunction('b', 2); //=> 'private state {a: 1, b: 2}' in console | |
MyCoolModule.bothPrivateAndPublicVariable; //=> 'private and public' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment