Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global variable

Status
Not open for further replies.

timgerr

IS-IT--Management
Jan 22, 2004
364
US
Is there a way to create a global variable that can be used anywhere within a script?

if I create a variable
Code:
var test = 'This will never change';
I want to use that variable anywhere, like in a function
Code:
function tryThis()
{
  alert(test);
}

When I run the function I want it to alert
Code:
This will never change

Can this be done?

Thanks,
timgerr

-How important does a person have to be before they are considered assassinated instead of just murdered?
-Need more cow bell!!!

 
[tt]<html>
<head>
<script language="javascript">
//method 1: test1; method 2: test2; method 3: test3
var test1; //decalred
function maketest1() {
test1="this is test1"; //no var here
}
function maketest2() {
window["test2"]="this is test2";
}
function maketest3() {
test3="this is test3"; //mostly due to sloppiness; rarely rationally make it like this consciously
}

function doit() {
alert(test1); //more tame declared
maketest1();
alert(test1);
alert(window['test2']); //more tame in this form
try {alert(test2)} catch(e) {alert("test2 is not defined")}; //more wild it is runtime:
maketest2();
alert(test2);
try {alert(test3)} catch(e) {alert("test3 is not defined")};
maketest3();
alert(test3);
}
window.onload=doit;
</script>
</head>
<body>
</body>
</html>[/tt]
 
Variables declared outside a function have document scope and can be used everywhere.
<script>
var myGlobal = "can be accessed anywhere";
function aFunction(){
alert(myGlobal);
}


There is no guarantee it will not be changed since there are no read only variables in javascript as far as I know. If you can read the variable you can write it.

You can put all global vars in a variable bag so they have a more robust name that is unlikely to be used in methods.
<script>
var varBag = {
value1:"string value 1",
value2:new Array(),
value3:33
}
function myF(){
alert(varBag.value1);
}



Greetings, Harm Meijer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top