0

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That means the variable should keep the value always. How then its garbage collected? If I didn't used the variable inside another function would it had lost the scope?
If the variable isn't used it will be garbage collected. If you remove the click handler outerValue could be cleaned up.
Is closures possible in a typed language?
The typing of a language has no effect on whether closures are possible. JavaScript is weakly typed but it might just as well be strongly typed.
Sorry, I meant compiled languages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.