Skip to content

Instantly share code, notes, and snippets.

@archan937
Last active March 1, 2020 22:31
Show Gist options
  • Save archan937/b30aa420319932294d5feaf8fd808994 to your computer and use it in GitHub Desktop.
Save archan937/b30aa420319932294d5feaf8fd808994 to your computer and use it in GitHub Desktop.
mod.js - A clean and lightweight implementation to define and extend from modules without exposing private members
var mod, define;
mod = (function() {
'use strict';
var modules = {};
return {
define: function(name, mod) {
modules[name] = (typeof(mod) == 'function') ? mod : function() { return mod; };
},
construct: function(identifier, init) {
var
fn = '__fn__', prop = '__prop__', body = [],
i, mod, module;
body.push('var IDENTIFIER = \'' + identifier + '\', ' + fn + ' = {};');
body.push('');
for (i = 2; i < arguments.length; i++) {
mod = arguments[i];
module = modules[mod];
if (mod.match(/\./)) {
mod = mod.replace('.', '_');
}
body.push('var ' + mod + ' = (' + module.toString() + '());');
body.push('');
body.push('for (var ' + prop + ' in ' + mod + ') { ');
body.push(' eval(\'var \' + ' + prop + ' + \' = ' + mod + '.\' + ' + prop + ');');
body.push(' eval(\'' + fn + '.\' + ' + prop + ' + \' = ' + mod + '.\' + ' + prop + ');');
body.push('}');
body.push('');
}
body.push(init.toString().replace(/(^function\s*\(.*?\)\s*\{\s*|\s*$)/, '').replace(/\}$/, ''));
return (new Function(body.join('\n'))());
}
};
}());
define = mod.construct;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>mod.js example</title>
<script type="text/javascript" src="path/to/mod.js"></script>
</head>
<body>
<script>
mod.define('Counter', function() {
var step = 3;
return {
counter: 0,
increment: function() {
return counter += step;
},
reset: function() {
counter = 0;
}
};
});
var Test = define(function() {
return {
incr: increment,
reset: reset
};
},
'Counter'
);
console.log(Test.incr()); // 3
console.log(Test.incr()); // 6
console.log(Test.incr()); // 9
console.log(Test.reset()); // undefined
console.log(Test.incr()); // 3
console.log(Test.incr()); // 6
console.log(Test.step); // undefined
console.log(Test.counter); // undefined
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment