Reputation: 1061
I'm using some libraries (like for example Less.js & Dojo) which require global config variables. For example:
less = { ... };
dojoConfig = { ... };
This works ok, but I'm wondering, should I declare this variables explicitly on window?
window.less = { ... };
window.dojoConfig = { ... };
What are pros & cons of each approach? what are pros & cons of referencing this variable from the actual code like (not considering possible name conflicts with local variables):
var somethingNew = dojoConfig.something;
The only thing I can think of is that code without window is prettier :)
Upvotes: 3
Views: 4010
Reputation: 14279
Explicitly attaching properties to window is easier to maintain than implicit global variable declarations. If you need to be flexible about the environment, you can use the following syntax:
//Here, "this" refers to the window when executed inside the browser
(function() { this.prop = "value" })()
console.log(window.prop === "value") // true
Within that function, you can add your private logic and expose the needed variables as needed. Also, you can name that function and attach those properties to any object you bind it to via function.prototype.bind
By the way, implicit globals also won't work in strict mode.
Upvotes: 1
Reputation: 3543
If you start running your code in strict mode, you'll find that it's illegal to create implicit globals by excluding var
or window.
.
IMO, it's just always a better practice to make your declarations explicit. For globals, that's either window.foo
or var foo
if you're in the global variable scope.
As far as referencing the existing global, it's just like any other variable at that point, so you don't really need window.
for that purpose, though you could use it if the variable is shadowed by a local variable with the same name.
Upvotes: 2