Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  130] [ 5]  / answers: 1 / hits: 120282  / 12 Years ago, wed, september 12, 2012, 12:00:00

(Maybe) I just solved a my problem (How to update front-end content after that a form is successfully submitted from a dialog window?) by storing / saving a variable in the JavaScript window object. However, since I am newbie in JavaScript matters, I have some doubts if storing / saving a variable in the JavaScript window object is a common / proper way to use that object. Is it?



For example, using the following code



$('.trigger').click(function() {
window.trigger_link = this;
});


is advisable?


More From » jquery

 Answers
11

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.


[#83111] Tuesday, September 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erinh

Total Points: 38
Total Questions: 100
Total Answers: 110

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;