简体   繁体   中英

Curious scoping difference between local/webserver and JS Bin test

It appears JS strict mode disallows declaring of implicit globals, but does not affect access of variables defined inside a conditional (if) or loop (while). In C# , you cannot access a variable declared within a conditional or loop externally. In JavaScript, however, the following works:

        "use strict";
        (function() {
            var mybool = true;
            if (mybool) {
                var test = "test;      
                console.log(test);      //"test"
            }
            console.log(test);          //"test"
        }());

But it breaks in JSBin and jsFiddle, saying that test1 is out of scope.

Why does it work on my webserver, but breaks elsewhere?. What are the rules on scoping within conditionals and loops and such... is JavaScript supposed to be like C# in this way?

I think you're getting strict mode and JSHint errors confused.

In JSBin, JSHint is issuing the 'test1' used out of scope error . This has nothing to do with strict mode. On your webserver, everything works correctly because strict mode has no opinions on this kind of variable scope issue. JSBin is running JSHint for you, and your web server is probably not.

What are the rules on scoping within conditionals and loops and such... is JavaScript supposed to be like C# in this way?

No. JavaScript has no block scope , but it does have function scope . This means that if a variable is declared inside of a block (like an if statement or loop construct), its declaration is "hoisted" to the top of the function. Check out this great article for more on variable declaration hoisting .

For your code in particular, it's interpreted just as if you've written it like this:

(function() {
    var mybool = true,
        test; /* = undefined */

    if (mybool) {
        test = "test;      
        console.log(test);      //"test"
    }
    console.log(test);          //"test"
}());

To avoid this kind of confusion over scope in JavaScript, it's a good practice to declare all of your variables at the top of the function they're in (since that's where they're actually scoped to anyway).

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