Reputation: 4864
In the script shown below
$(function(){
var outerValue="OuterValue";
$('#btnScope').click(function(){
alert(outerValue);
});
});
The outer function (ie $()
) executes when the page loads. At this time click event will be bound to anonymous function (which alerts). This function uses value of outerValue
which might have lost scope after completing the ready($()
) function. How this is possible? How could I know the scope of variable?
How the interpreter define its scope?
Upvotes: 0
Views: 81
Reputation: 57721
The outer scope is not lost. The scoping as you describe it is fairly accurate.
A variable's scope is roughly where it's defined (where var
is). Any inner scope can access anything in it's outer scope. Only functions have scope though; not if
, for
, while
or switch
.
Upvotes: 3