Last active
January 21, 2019 11:37
-
-
Save sdd/6371360 to your computer and use it in GitHub Desktop.
Javascript Module pattern template.
Shows a class with a constructor and
public/private methods/properties. Also shows compatibility with CommonJS(eg Node.JS)
and AMD (eg requireJS)
as well as in a browser.
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
/** | |
* Created with JetBrains PhpStorm. | |
* User: scotty | |
* Date: 28/08/2013 | |
* Time: 19:39 | |
*/ | |
;(function(global){ | |
"use strict"; | |
var M = function() { | |
// Constructor. arguments are passed | |
// from Module() call. this refers to m. | |
function init() { | |
meth_priv2(); | |
m.meth_pub2(); | |
} | |
// Empty object, to be populated with | |
// public properties and methods. | |
var m = {}; | |
// Private properties. define using var x. | |
// closure keeps them private. | |
var prop_priv = "private property"; | |
// public properties. define using m.x. | |
m.prop_pub = "public property"; | |
// private methods. define as var x = function() {} | |
// closure keeps them private. | |
var meth_priv = function() { | |
console.log(prop_priv); | |
console.log(m.prop_pub); | |
}; | |
var meth_priv2 = function() { | |
// access another priv method | |
meth_priv(); | |
// access a pub method | |
m.meth_pub(); | |
}; | |
// public methods. define as m.x = function() {} | |
// private props/methods accessed via x. | |
// public props/methods accessed via m.x | |
m.meth_pub = function() { | |
console.log(prop_priv); | |
console.log(m.prop_pub); | |
}; | |
m.meth_pub2 = function() { | |
// access a priv method | |
meth_priv(); | |
// access another pub method | |
m.meth_pub(); | |
}; | |
// call the constructor | |
init.apply(m, arguments); | |
return m; | |
}; | |
// determine correct export method depending upon | |
// environment that this script was loaded in: | |
if (typeof module != 'undefined' && module.exports) { | |
module.exports = M; // Node / CommonJS... | |
} else if (typeof define === 'function' && define.amd) { | |
define('Module', [], M); // or RequireJS / AMD... | |
} else { | |
global.Module = M; // or browser | |
} | |
})(this.window || global); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Influences:
http://www.2ality.com/2011/08/universal-modules.html
https://github.com/millermedeiros/crossroads.js/blob/776f603c/dist/crossroads.js#L340-357
http://www.2ality.com/2012/07/amdefine.html
http://www.sitepen.com/blog/2010/09/30/run-anywhere-javascript-modules-boilerplate-code/
http://addyosmani.com/writing-modular-js/