简体   繁体   中英

How come my inner inner function has access to outside global-scope variables? Isn't that a violation of scope/closure?

I was trying to consolidate my understanding of closure/scoping in JavaScript with the following test code:

var globalM = 1;

function firstFx() {

    function secondFx () {
        console.log(globalM + 1);
    }

    secondFx();
}

firstFx();

I know firstFx would have access to globalM because it's within it's scope. But how is it that my inner inner function, secondFx also has access to the globalM variable? It's reaching 2 levels out, I thought that wasn't possible? Yet the result of 2 is getting logged to the console.

Your second function has access to it because the variable is global. That means that all scopes anywhere have access to it.

Any scope can access anything that is declared globally or in a level higher. For example in your function the inner function could also access any variables declared in your outer function.

There isn't a limitation on the levels of scoping, it goes all the way out to the global scope.

The scope of the code in a function is the scope where the function was created plus its own scope.

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