Are there any repercussions to storing globals like this? - javascript

So I know polluting the global namespace referencing the window is a bad thing, especially if you have multiple 3rd party references. So this would be not desirable:
window.someObject = someObject;
That will reference it everywhere. What if I instead use it like this?
var MyApplication = window.MyApplication;
MyApplication.someObject = someObject;
Of course using this approach requires referencing MyApplication = window.MyApplication at the top of each module that needs access to this created namespace. So back to my question. Is this an acceptable approach to giving global access without polluting the window global namespace?

If you want global access, you need to have a global of some sort. This is the common way of doing it.
An example from the jQuery source code:
_jQuery = window.jQuery,
_$ = window.$,
I believe all of the big frameworks do it this way. I'd consider it perfectly acceptable to pollute the global namespace with one container variable.

You can also do (in global context):
(function(lib) {
// in here, lib references window.MyApplication
...
}(MyApplication));
So you can easily change the object passed in.

Related

Is a Local Reference to the Global Scope Itself Fundamentally a Bad Idea?

Forgive my ignorance or paranoia if this is a stupid question, but I can't seem to find anything on this specific situation in particular (which leads me to think maybe most people either know to avoid it or have better ways to handle this).
Here's the premise: I don't know whether or not my code will necessarily always be ran in a browser, and as such, I don't know if I'll have access to window (specifically by that name) or if that scope will be named something else in whatever environment my code may find itself in.
So my idea was to find that scope once, assign it to a local variable then let everything within my function just reference that local variable if I ever need to access the global scope instead of reaching for window (again, it could be called something else—I won't know).
My concern is, is this going to cause some memory leak issue (or maybe it's a bad idea for other reasons)? Is there something I should be mindful of or am I good to go?
function myConstructor() {
// Is this fundamentally a bad idea?
var globalScope = findGlobalScope() // Cyclic reference here?
function findGlobalScope() {
// Let's say I had some logic here that
// determinded that I'm running this code
// in a browser, so now I know `window`
// is where my global variables are.
// Keep in mind it may not always be `window`,
// but let's say this time it is.
return window
}
this.doWork = function() {
// In here I reference the `globalScope` variable
// instead of the `window` variable explicitly.
//
// I'm doing it this way because I don't want
// my code to break if I run it outside of a browser
// where I might not have access to an object explicitly
// named "window"
console.log(globalScope) // instead of console.log(window)
}
}
var myObj = new myConstructor()
// Now `myObj` is located at `window.myObj`
// and `myObj` has a reference to `window`
// which... again, has a reference to window.myObj
// Is this something I should be concerned about?
I appreciate the help.
It's not a scope, it's an object. (But it's understandable you'd think of it as a scope; it's used by one of the global scopes to hold variables.¹)
That's absolutely fine, it's not going to cause leaks or anything. That's one object that you know won't be going away (unless your code does, too).
Note that JavaScript now has globalThis, which is exactly what you're looking for. :-) It's a relatively recent addition.
That said, as Taplar mentioned, ideally your code shouldn't care about the global object, and should avoid creating global variables entirely if possible. The global namespace is crowded — and extremely crowded on browsers.
Ways to avoid using global scope:
Use modules. Modern environments support ES2015's modules. Older environments can be supported via bundlers like Webpack or Rollup.js.
If you can't use a module, use a wrapper function. If necessary because your code must be split across files at runtime, have that function expose a single obscurely-named global that has properties on it for your other things.
Example of #2 (using ES5 syntax):
var myStuff = myStuff || {};
(function() {
myStuff.doSomething = function() {
// ...
};
})();
¹ This is an interesting, but confusing, part of JavaScript: There are at least two global scopes in JavaScript, and outer one and an inner one (which is new in ES2015+).
The outer one has "variables" that are properties of the global object, either inherited ones or own properties: If you use a variable name, and it doesn't exist in the current scope or one between the current scope and the global scope, but does exist as a property on the global object, the property on the global object is used — an old-style global variable. When you declare a function at global scope, or declare a variable with var, it adds a property to the global object. The global object also (in most environments) inherits things from its prototype and its prototype's prototype. For instance, globals created on browsers for elements with an id are properties of the WindowProperties object, which is in the prototype chain of the global object. It also sometimes has other "own" properties, such as name (the name of the window on browsers).
The inner global scope doesn't use the global object. It's where things declared with let, const, and class go. They don't become properties of the global object.

JavaScript - global namespace, window or nothing?

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 :)
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.
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.

javascript storing global variables in DOM

I have a fairly large script that contains about 60 global variables. I'm thinking about using the namespace pattern to encapsulate my script and have only one global variable that references one object.
Even though this pattern is considered best practice, I'm also thinking about an alternative: storing the global variables inside the DOM, in hidden divs, and accessing them with $('#MyGlobalVar1').text(). Is this a good idea or not?
Thanks for your suggestions.
No, this is not a good idea.
It pollutes the DOM with non-semantic data, and is less efficient as well. That's even worse than polluting the global JS namespace, and worse still, it only allows you to store strings.
Even if I would recommend you to use a namespace object to hold and reference your data, you can simply put an outer self-invoking function around your code to prevent clobbering the global object.
So you go from
var global1 = true,
global2 = true;
into
(function() {
var global1 = true,
global2 = true;
// rest of all app logic
}());
Beyond that, since you're using jQuery you also might to use jQuerys .data() method. It's designed to reference data for a specific node, but it's internally stored into an ECMAscript object also.

How to preserve global variables in javascript when using Closure compiler with advanced optimization?

I have my own Javascript library, which I want to minify by using Google closure compiler with Advanced optimization. By looking at the docs I see how to declare functions which are used outside of the library.
However I couldn't find a way how to preserve global variables declared in my library. Closure compiler just removes them, because it thinks they are never used. Anybody can help ?
Edit: example code:
var variable_1 = true;
This is defined globally right at the beginning of my library, but it's never used in the library itself. It is used outside the library when it is included in some page. But that Closure compiler doesn't know and thats the reason it removes these declarations.
The closure compiler cannot remove global variables declared as window["variable_1"] = true
I recommend you write to window directly for global variables and I also recommend you use string literals for your variable names so that closure doesn't minify it.
Although you can refer to a "true" global variable through replacing all usage of that global variable with window["varname"], it is usually not a good idea to "pollute" the global namespace. The Closure Compiler is designed to discourage you from doing this.
CAVEAT: window["varname"] and var varname are not the same, as "window" may not always be the global object in non-browser environments. As a matter of fact, the Closure Compiler assumes that the global object and "window" are different. For example, window["varname"] will compile to window.varname instead of var varname. They are NOT the same, although in a browser they work similarly.
It is best to make a global namespace object, then only export that one object. All your "global" variables should become properties under this global namespace variable. Benefits:
All those global variables are renamed to shorter versions
Inlining of constants can happen
The Closure Compiler automatically "flattens" the namespace anyway, so your code won't be any slower
Superior obfuscation
Your code also works in non-browser environments. Remember, "window" may not always exists (e.g. in server-side code) and the "global object" may not always be "window"
If you have global variables that the user must read/set to use your library, it is also discouraged. It is better to expose an API on the global namespace object, then expose the public API's as usual through the window object: window["myLib"]["setConfig"] = myLib.setConfig.
In your case, if you have global variables used in other parts of your non-Closure-Compiled code, you have to consider:
Is it better to put the declaration of those variables outside of the file being compiled by Closure
Why are you not putting the declaration of those variables together with the code using them
Should you actually be Closure-compiling all the code instead of only a portion (it is possible? Do you use another library?)
I've just come across this, and I have my own solution.
Create you're entire library within a self-executing function, putting all the object properties as strings (at least once for each property) like so:
(function () {
var myLibrary = {
'myMethod' : function () {
...
}
}
myLibrary.myMethod['propertyOfTheMethod'] = '';
}());
The usual way to make this accessible from the outside would be to put var myLibrary = before the function and return myLibrary at the end of it so that it gets assigned to a global variable. But the function is executed in the global scope (because it's self-executing), so we can create a property of this using a string literal. So in full:
(function () {
var myLibrary = {
'myMethod' : function () {
...
}
}
myLibrary.myMethod['propertyOfTheMethod'] = '';
this['myLibrary'] = myLibrary;
}());
But, this won't work under "use strict";. The best way to get the global variable in strict mode is with var global = Function('return this')(); then assign your variable to that.

How to cleanly deal with global variables?

I have a number of aspx pages (50+).
I need to declare a number(5-7) of global variables in each of these pages.
Variables in one page independent of the other pages even though some might be same.
Currently I am declaring at the page top and outside of any function.
Should I approach this differently and is there any side effects of this approach?
If exact duplicate, please let me know.
Thanks
It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.
Create a namespace for yourself
https://www.geeksforgeeks.org/javascript-namespace/
More here: https://stackoverflow.com/search?q=namespace+javascript+global
Some examples using different methods of setting the vars
myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}
As #mplungjan says, best practice is to avoid global variables as much as possible.
Since window is global, you can declare a namespace at any time and within any function by using window.NAMESPACE = {};
Then you can access NAMESPACE globally and set your values on it as properties, from within the same or another function:
NAMESPACE = { var1:"value", var2:"value" /* etc */ };
If you can do all this within script files rather than directly in your page then so much the better, however I guess you may not have the values available in a static script.
One approach would be to declare the variable on "root" level, i.e, outside any code blocks before any other JS code tries to access it.
You can set global variables using window.variablename = value; in order to keep it clean superficially atleast.

Categories