Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created September 19, 2011 14:23
Show Gist options
  • Select an option

  • Save cowboy/1226607 to your computer and use it in GitHub Desktop.

Select an option

Save cowboy/1226607 to your computer and use it in GitHub Desktop.
JavaScript: exports ideas
// Not great because `addOne` is always created in the current scope (which is
// global when addone.js is included normally).
var addOne = (function() {
return function(n) {
n + 1;
};
}());
addOne(2) // 3
// If you want `thing` to be private, you'd need to include the addOne module
// INSIDE your module. Which means if you're concatenating JS files together,
// things can get really gross. This won't work if you're just including the
// three .js files in 3 SCRIPT elements (for development).
// intro.js
(function() {
// addone.js
var addOne = (function(global) {
return function(n) {
n + 1;
};
}(this));
// outro.js
addOne(2) // 3
}());
// This is better because `addOne` is created as a property of the current
// `this` which defaults to the global object if addone.js is included
// normally... but can be overridden VERY easily.
(function(global) {
global.addOne = function(n) {
n + 1;
};
}(this.exports || this));
addOne(2) // 3
// By defining window.exports, you can do whatever the hell you want. Each one
// of these files can be included separately for development or concatenated
// into one large file. More flexibility = win.
// bocoup.js
var Bocoup = {};
// bocoup.utils.js
Bocoup.utils = this.exports = {};
// addone.js
(function(global) {
global.addOne = function(n) {
n + 1;
};
}(this.exports || this));
// main.js
delete this.exports;
Bocoup.utils.addOne(2) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment