Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com
Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com
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 on Friday, September 5, 2008 12:39 PM CSS/DHTML/JavaScript | Back to top


Comments on this post: Javascript variable declaration scope is different from C#.

# re: Javascript variable declaration scope is different from C#.
Requesting 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.
Left by Owen McGovern on Apr 27, 2009 8:02 PM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net