Skip to content

Instantly share code, notes, and snippets.

@donbrae
Last active August 18, 2020 12:59
Show Gist options
  • Save donbrae/9176e49a49e3fb5e5733922de32ac3d5 to your computer and use it in GitHub Desktop.
Save donbrae/9176e49a49e3fb5e5733922de32ac3d5 to your computer and use it in GitHub Desktop.
Basic JavaScript module pattern
/**
* @name MY_MODULE
* @author Jamie Smith
* @description Basic JavaScript module template with config and state objects, and private and public functions
*/
const MY_MODULE = (function () {
"use strict";
const cfg = {
foo: 'bar'
};
const state = {
init: false
};
function init() {
// ⋯
console.log(this.Utils.helperFunction('Foo bar'));
state.init = true;
}
function getState(property = null) {
if (property)
console.log(property, state[property]);
else
console.log(state);
}
function privateFnc() { }
function publicFnc() {
privateFnc();
}
return {
init: init,
getState: getState,
publicFnc: publicFnc
};
})();
// ⋯
// Sub-module (note that this sub-module's methods will be publicly callable)
MY_MODULE.Utils = (function () {
"use strict";
// Example helper function
function helperFunction(value) {
if (value)
return `${value}-amended`;
return null;
}
return {
helperFunction: helperFunction
};
})();
// ⋯
MY_MODULE.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment