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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable scope

Status
Not open for further replies.

ckennerdale

Programmer
Dec 23, 2000
158
0
0
GB
Can anyone explain why this code writes 'no' in the document when I expect it to write 'yes'

<html>
<head>
<script>
var pressed = 0;
function Test(){

if (document.pressed == 0){
document.write(&quot;yes&quot;);
}else{
document.write(&quot;no&quot;);
}
}

</script>
</head>
<body onload=&quot;Test()&quot;>
</body>
</html>


Thanks in advance Caspar Kennerdale
Senior Media Developer
 
using a . after document makes you access part of the DOM of document.

for example document.write is a method associated with document.

pressed is not a property of the document but a global variable.

when you wrote if (document.pressed) you only checked to see if document had a property or function named pressed.

<html>
<head>
<script>
var pressed = 0;
function Test()
{
if (pressed == 0)
{
document.write(&quot;yes&quot;);
}
else
{
document.write(&quot;no&quot;);
}
}
</script>
</head>
<body onload=&quot;Test()&quot;>
</body>
</html> Gary Haran
 
I'm not sure if this fully explains it to you but by removing the 'document' from the equation you'll get 'yes' for your answer. I don't believe global variables are stored as part of the document object, however if you destroy the document you destroy the variables so something in the document retains the variables.

if (pressed == 0){
document.write(&quot;yes&quot;);
}else{
document.write(&quot;no&quot;);
}


You can see the document properties using the script below.

<script language=&quot;javascript&quot; type=&quot;text/javascript&quot;>
<!--
var str = &quot;&quot;;
for(i in document){
str += i+&quot;: &quot; + document + &quot;\n&quot;;
}
alert(str);
</script>

the same can be done with the properties of the document properties, eventually you'll find the area where the variables are stored.

Hope this helps
RnK

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top