简体   繁体   中英

How inner anonymous function have scope of outer function?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM