Click to See Complete Forum and Search --> : lifetime/scope of a variable - am I right


Benoni
08-06-2003, 05:55 AM
Hello,
Could anyone please tell me if I am right or wrong, and wether these bits of code are compatiable on most/all java browsers.

In JavaScript:

Using:
var $myvar = "hello";

Creates a variable with a lifetime untill that function ends, and scope of that function only.


Using:
$myvar = "hello";

Creates a variable with a lifetime of the length the page is loaded and a scope of ALL.
It can be retreived on the same page in a different function using alert($myvar); or from another page in a frames page using alert(top.framename.$myvar);


I also noticed that creating my own tag in HTML code can be read/written to using Javascript:
<body id="bodytag" mybodyvar="hello">
alert(bodytag.mybodyvar);
I think this works - Does it work on most/all Java browsers.
I also think just setting such a tag using JavaScript without setting it up in the HTML code alos works - How compatable is that?
Thanks a lot
Benoni

Charles
08-06-2003, 06:40 AM
1) "A JavaScript identifier, or name, must start with a letter or underscore ('_'); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters 'A' through 'Z' (uppercase) and the characters 'a' through 'z' (lowercase)." (http://devedge.netscape.com/library/manuals/2000/javascript/1.3/guide/ident.html#1008330)

2) In client side JavaScript you cannot really create global variables; those are really properties of the Window object. When making properties of a Window object using "var" does nothing at all. However, when you make a variable inside of a function using "var" the variable is really a property of the call object and will be discarded when the function returns. Omitting the "var" inside of a function will create a property of the Window object that will persist after the function returns.

3) You are not supposed to be able to be able to make up your own parts of HTML and you will find that often you cannot. You can, however, add properties and methods to any Object using JavaScript.

<script type="text/javascript">
<!--
document.getElementsByTagName('body')[0].foo = 'Foo';
alert (document.getElementsByTagName('body')[0].foo);
// -->
</script>