We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.
Typically, we do something like:
grid.js
var myGrid = .....
combos.js
var myCombo = .....
Then, in our application code, we:
application.js
function blah() { myGrid.someMethod() }
someother.js
function foo() { myCombo.someMethod(); myGrid.someMethod(); }
So, should we be using the var myGrid
or is better to use window.myGrid
What's the difference?
Scoping — the main reason to avoid var var variables are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } . Let's understand what that means via code. console.
The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object).
Variables declared using var can be done anywhere in a function. But instead of being limited to block, like a for loop, in the function the variables are hoisted to the top of the function. This is why the best practice is to declare all the variables used in a function at the beginning of the function.
No difference. They both have the same effect (In the browser, where window is the global context1).
A potentially important difference in functionality is that window.myGrid
can be delete
d, 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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With