Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
// One limitation of the module pattern so far is that the entire module must be in one file.
// Anyone who has worked in a large code-base understands the value of splitting among multiple files.
// Luckily, we have a nice solution to augment modules.
// First, we import the module, then we add properties, then we export it.
var MODULE = (function (my) {
my.anotherMethod = function () {
// added method...
};
return my;
}(MODULE));
// This pattern is perhaps the least flexible option.
// It does allow some neat compositions, but that comes at the expense of flexibility.
var MODULE_TWO = (function (old) {
var my = {},
key;
for (key in old) {
if (old.hasOwnProperty(key)) {
my[key] = old[key];
}
}
var super_moduleMethod = old.moduleMethod;
my.moduleMethod = function () {
// override method on the clone, access to super through super_moduleMethod
};
return my;
}(MODULE));
(function ($, YAHOO) {
// now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));
var MODULE = (function (my) {
// add capabilities...
return my;
}(MODULE || {}));
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};
return my;
}());
// Tight augmentation implies a set loading order, but allows overrides.
var MODULE = (function (my) {
var old_moduleMethod = my.moduleMethod;
my.moduleMethod = function () {
// method override, has access to old through old_moduleMethod...
};
return my;
}(MODULE));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.