I asked here: node.js require inheritance?
and was told that I can set variables to the global scope by leaving out the var.
This does not work for me.
ie:
_ = require('underscore');
Does not make the _ available on required files. I can set with express's app.set
and have it available elsewhere though.
Can somebody confirm that this is supposed to work? Thanks.
What about a global namespace like
global.MYAPI = {}
Edit after camilo-martin's comment: All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.
@tip: http://thanpol.as/javascript/development-using-namespaces/
The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.
Use a JS file then use module exports.
Example:
globals.js
Then if you want to use these, use require.
I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:
Yes, taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or atleast somewhere to:
Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.
Also too, if this is wrong then please let me know as I've only just started doing this recently
global._ = require('underscore')
Note that using
GLOBAL
is deprecated:My comment:
If you know what you're doing, I think its OK to use global. When I'd have to require some library every time I want to use it (and let's say I'm using it in tens or hundreds of files) I think it destroys the main point of a lot of libraries that are made to be easy and quick to use. Why is it named
_
, notamazingLibraryCalledUnderscore
?So for me, needing to write 30 chars of
var _ = require('underscore');
is3000%
more than required minimum (1 char). Yes. I'm obsessed about making my life easier when writing the code. I just hate repeating obvious things. If I once told damn node what I mean byI want you to know _ means I use underscore
I don't want to say it again.So - I believe when you control your code, you should try to make it sexy. I believe writing 30 chars every time to do so simple thing is damn ugly!
ps. to trust yourself when you say
I control my code
, you need to have experience of loosing this control at least once.You can just use the global object.