-
-
Save rauschma/7960405 to your computer and use it in GitHub Desktop.
(function (glob) { | |
// glob points to global object | |
}(typeof window !== 'undefined' ? window : global)); |
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.
The first approach doesn’t work in Node.js modules, because in module scope,
this
does not refer to theglobal
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.
Absolutely! Language shims may be another use case, but also a rare one.
Why not just
(function(root) { /* use |root| here */ }(this));
or, if you’re in an untrusted environment (wherethis
may refer to something other than the global object),Function('return this')();
?