Last active
August 29, 2015 14:02
-
-
Save christianbundy/37dfebe291bd5fbdebd0 to your computer and use it in GitHub Desktop.
Export variables to the global namespace with `module.exports` in the browser (or anywhere else). Example in the comments!
This file contains hidden or 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
// Initialize an empty module object | |
module = {}; | |
// Functions created this way don't inherit strict mode | |
exports = Function('return this')(); | |
// Define what happens when you try to get or set `module.exports` | |
Object.defineProperty(module, 'exports', { | |
// Extend the top-level object with the object that's passed | |
set: function (obj) { | |
for (var prop in obj) { | |
// Don't set properties inherited from the prototype | |
if (obj.hasOwnProperty(prop)) { | |
exports[prop] = obj[prop]; | |
} | |
} | |
}, | |
// Return the top-level object | |
get: function () { | |
return exports; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let's pretend we need to export
foo
to the global namespace (usuallywindow
on the client andglobal
on the server), but that our code needs to be able to run on any environment.Sure, you could probably do some typechecks, but hard coding variable references, blindly trusting your scope, and typechecking random variables are going to give you more problems than they're worth.
You could just use some JavaScript gymnastics, but nobody deserves to be subjected to this shit.
Instead, just use the tried-and-true
module.exports
to export your local variables to the global namespace.It's clean, it's easy, and it's now compatible with every modern environment.