Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 561
kheya Avatar asked Feb 21 '11 08:02

kheya


People also ask

How do you get around a global variable?

Function Arguments. The simplest way to avoid globals all together is to simply pass your variables using function arguments. As you can see, the $productData array from the controller (via HTTP request) goes through different layer: The controller receives the HTTP request.

What are two reasons why you should not use global variables?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.


1 Answers

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)} 
like image 152
mplungjan Avatar answered Oct 08 '22 19:10

mplungjan