window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Globals are generally to be avoided. You should define variables within the scope of functions.
Answer from marteljn on Stack Overflowwindow.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Globals are generally to be avoided. You should define variables within the scope of functions.
Global variables in JavaScript are attached to the "global object", which in a browser environment is aliased to window object - this is why you can refer to a global variable either as variableName or window.variableName.
It's also worth mentioning that using global variables in JavaScript is not considered good coding practice.
Here's a good and very detailed explanation.
The window variable and temporarily storage
javascript - Window vs Var to declare variable - Stack Overflow
javascript - Should I use window.variable or var? - Stack Overflow
Accessing browser window variables
Videos
window.ABC scopes the ABC variable to window scope (effectively global.)
var ABC scopes the ABC variable to whatever function the ABC variable resides in.
var creates a variable for the current scope. So if you do it in a function, it won't be accessible outside of it.
function foo() {
var a = "bar";
window.b = "bar";
}
foo();
alert(typeof a); //undefined
alert(typeof b); //string
alert(this == window); //true
A potentially important difference in functionality is that window.myGrid can be deleted, and var myGrid can not.
var test1 = 'value';
window.test2 = 'value';
console.log( delete window.test1 ); // false ( was not deleted )
console.log( delete window.test2 ); // true ( was deleted )
console.log( test1 ); // 'value' ( still accessible )
console.log( test2 ); // ReferenceError ( no longer exists )
I would suggest creating a namespace variable var App = {};
App.myGrid = ...
That way you can limit the pollution of the global namespace.
EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:
- You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)
- You encapsulate your methods in objects that get instantiated with the components you have
ex: you have
function foo() {
myCombo.someMethod();
myGrid.someMethod();
}
becomes:
var Foo = function(combo, grid) {
var myCombo = combo;//will be a private property
this.myGrid = grid;//will be a public property
this.foo = function() {//public method
myCombo.someMethod();
myGrid.someMethod();
}
}
App.myFoo = new Foo(someCombo, someGrid);
App.myFoo.foo();
this way you limit the amount of little objects and only expose what you need (namely the foo function)
PS: if you need to expose the internal components then add them to this inside the constructor function
In JavaScript, any global variable is actually a property of the window object. Using one is equivalent to (and interchangeable with) using the other.
Using global variables is certainly "common," so the question is whether or not it's "proper." Generally, global variables are discouraged, because they can be accessed from ANY function and you risk having multiple functions trying to read from and write to the same variables. (This is true with any programming language in any environment, not just JavaScript.)
Solve this problem by creating a namespace unique to your application. The easiest approach is to create a global object with a unique name, with your variables as properties of that object:
window.MyLib = {}; // global Object container; don't use var
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7
Another approach is to use .data() to attach variables to a relevant DOM element. This is not practical in all cases, but it's a good way to get variables that can be accessed globally without leaving them in the global namespace.
What is actually not mentioned here, and is probably the biggest deal breaker on why not to use window as global scope carrier is that it can be frozen (not writable) in some cases (and I'm talking from production based experience).
A good pattern is actually just create a global variable that will be used for all the common stuff in your application
var Application = {};
Application.state = { name: 'Application' }
.
.
What I found as the best pattern for me in javascript is to have a global state using Redux.
If this code is executed in a browser, window is available as a global object. However, if this code is executed in a node environment (server side), window will be undefined.
Here's one way to handle this if your code will execute both server-side (node environment) and client-side (browser environment):
if (typeof window !== 'undefined') {
configs = {
//firebase configuration
apiKey: window._env_.API_KEY,
projectId: window._env_.PROJECT_ID,
messagingSenderId: window._env_.MESSAGING_SENDER_ID,
backendURL: window._env_.BACKEND_URL
}
} else {
// handle server-side logic here
}
If there's no need for this to execute in the browser, it would be simplest to just use process.env instead of setting these variables on the window. If you do need these variables in both places (and they're coming from process.env), this might be another solution:
const env = typeof window === 'undefined' ? process.env : window._env_;
export const configs = {
//firebase configuration
apiKey: env.API_KEY,
projectId: env.PROJECT_ID,
messagingSenderId: env.MESSAGING_SENDER_ID,
backendURL: env.BACKEND_URL
}
You should create a new js file, then write as below. File name is appsettings.js
window.appSettings = {
apiKey: '${REACT_API_KEY}',
projectId: '${REACT_PROJECT_ID}',
messagingSenderId: '${REACT_SENDER_ID}',
backendURL: '${REACT_BACKEND_URL}'
};
env files
REACT_API_KEY=value
REACT_PROJECT_ID=value
REACT_SENDER_ID=value
REACT_BACKEND_URL=value
Public/index.html
<script src="http://localhost/appsettings.js?v={version}"></script>
<script>
window.appSettings.apiKey= '%REACT_API_KEY%';
window.appSettings.projectId= '%REACT_PROJECT_ID%';
window.appSettings.messagingSenderId= '%REACT_SENDER_ID%';
window.appSettings.backendURL= '%REACT_BACKEND_URL%';
</script>
Where you want to use, write this code
window.appSettings.apiKey
Not need declare another place because it declare index.html
I've been reading through the MDN documentation, but it doesn't really explain why this is needed. What actually gets stored in the global window object?
edit:
Found a good answer on stackoverflow!