Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created December 14, 2013 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rauschma/7960405 to your computer and use it in GitHub Desktop.
Save rauschma/7960405 to your computer and use it in GitHub Desktop.
Cross-platform way of referring to the global object.
(function (glob) {
// glob points to global object
}(typeof window !== 'undefined' ? window : global));
@mathiasbynens
Copy link

Why not just (function(root) { /* use |root| here */ }(this)); or, if you’re in an untrusted environment (where this may refer to something other than the global object), Function('return this')();?

@rauschma
Copy link
Author

The first approach doesn’t work in Node.js modules, because in module scope, this does not refer to the global object. I’m intrigued that the second approach works, but I try to stay away from eval and Function as much as I can.

@mathiasbynens
Copy link

The first approach doesn’t work in Node.js modules, because in module scope, this does not refer to the global object.

True (and that’s covered by my second solution) but when do you need a reference to the real global object in Node.js modules? Not very often. Most of the time you just want to assign something to module.exports so that it can be used outside of the module.

That said, here is an example of an exception to this, where a CSS property is added to the global object: https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js But other than weird DOM polyfills like this I don’t think there’s a real use case for getting the true global object in a Node.js module.

@rauschma
Copy link
Author

Absolutely! Language shims may be another use case, but also a rare one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment