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:

# re: Javascript variable declaration scope is different from C#.

Left by Owen McGovern at 4/27/2009 8:02 PM
Gravatar
> It's well known that JavaScript is similar to C++/C#

It certainly is not.
C++ is strongly data typed, Javascript is not.
To the layperson, at first glance a Javascript expression syntax looks vaguely like C-like.

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345