Javascript variable declaration scope is different from C#.

It's well known that JavaScript is similar to C++/C#, but doesn't required explicit declaration of the variables.
However, it worth to read specification(e.g.  http://jennifermadden.com/javascript/variables.html )  to understand subtle differences.
 
I didn't know, that a variable implicitly declared within a function is  a global variable.
For example,
function foo() {
        g= 17;//it's global, will be visible outside the function after the function will be executed
          var x = 17;//local, not visible outside the function
}
          foo();
          println(g);//17
          println(x);//undefined
 
another rule(UPDATE:known browsers do not support it) : Depending on the system in which JavaScript is embedded, other objects whose scopes enclose the function currently executing (if any) are searched, starting from the innermost object, for a property identified by the simple name. If found, the simple name's scope is the object containing the property.
I understood the rule as it is not nesessary to pass local variables as parameters to calling function, but the calling function can see parents variables.
 
function foo() {
         var x = 17;//local, but should be visible in calling function according to the rule
         foo1();   
}
function foo1() {
          println(x);//should be 17 if called from foo, but known browsers do not support it.
}
However as it was pointed by Nitin Reddy Katkam,  neither Firefox's nor Internet Explorer's nor Safari implementation of Javascript  support this rule.
Also note, that in JavaScript constructor var can be used to implement private members and this to implement public fields. See "Private Members in JavaScript" article.

posted @ Friday, September 05, 2008 12:39 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 2 and 4 and type the answer here:
 

Live Comment Preview:

 
«December»
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910