Jump to content

Making A Variable Globa/constantl?


EmperorZenos

Recommended Posts

Well the idea struck me on making a truly constant/global variable.I'm pretty sure that we've all stated a var A as 1 then in function abc() we call for A and set it to be 2. Then in function def() we call for A, intending it to be 2, and it ends up to be 1.I had an idea that, instead of variables being stored in scripts, have them stored on the web page. With a bit of style to make them invisible, of course. So, a <span id="A_h"> element would hold var A as 1, then in abc() we call for A_h and set it to be 2, and set var A as two as well (if intended to be used). Then in def() we would call for A_h and get the value of A and use that value. Example code:

 <span id="A_h" style="[...]">1</span>[...]<script type="text/javascript">var A_f=document.getElementById("A_h").innerHTML;var A=Number(A_f);[...]function abc() {var A=2;document.getElementById("A_h").innerHTML=2;[...]}[...]function def() {var a_if_f=document.getElementById("A_h").innerHTML;var a_if=Number(a_if_f);if (a_if==2) {[...]}[...]}[...]</script>

I haven't tried this yet, but I'm wondering if anyone can tell me if this would work or not, I'm a bit busy at the moment. Thanks.Edit: Domestically constant.

Link to comment
Share on other sites

Any variable you define in a script outside a function is global. Any variable you define inside a function but without using the keyword "var" is global.What more do you want?

Link to comment
Share on other sites

This would work, you could even use hidden inputs which are often used for similar purposes, but I have to agree with with Deirde's Dad why would you need to do that unless you are passing it to the server side. You could still assign the span twice if it was in the same html form.

Link to comment
Share on other sites

Javascript doesn't have support for constants like other languages, but the scoping rules are pretty clear and easy to understand, it supports global variables just fine. You can also create a single global object and store all of your global values as properties on the one object.

Link to comment
Share on other sites

Any variable you define in a script outside a function is global. Any variable you define inside a function but without using the keyword "var" is global.What more do you want?
I mean editing a variable inside a function then in an other function use that edited value from that variable.
Link to comment
Share on other sites

I mean editing a variable inside a function then in an other function use that edited value from that variable.
That's how global variables work:
<script type="text/javascript">var test = 5;function altertest(){   test = test * 5;}function writetest(){	document.write(test + "<br />");}writetest();altertest();writetest();altertest();writetest();</script>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...