Reputation: 845
Why does the alert print 2 in the below example? var a is unknown to function n...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Test Doc</title>
<script type="text/javascript">
var a = 1;
function f() {
var a = 2;
function n() {
alert(a);
}
n();
}
f();
</script>
</head>
<body>
</body>
</html>
Upvotes: 1
Views: 466
Reputation: 11844
a
is decalred as a global variable and given a value of 1. a
is also declared inside the function f()
and given a value of 2. Function n()
is declared inside the function f()
and called after the assignment to the "inner" a
.
So when n
is called, the identifier a
will be resolved from the scope of n
. The first variable object on the scope chain with an a
property is the one declared in f
, so its value is returned.
Upvotes: 0
Reputation: 490283
JavaScript functions inherit their parent's scope. Inner variables shadow parent scope variables with the same name.
Upvotes: 5
Reputation: 8118
It would alert "2".
Test your javascript examples here : jsfiddle.net
Your example is pasted here : your javascript example
And why the heck is var a
unknown to n() ??
Upvotes: 0