JavaScript scope in a try block

后端 未结 6 1843
礼貌的吻别
礼貌的吻别 2020-12-30 20:37

Say I\'m trying to execute this JavaScript snippet. Assume the undeclared vars and methods are declared elsewhere, above, and that something and something

6条回答
  •  一向
    一向 (楼主)
    2020-12-30 21:09

    • In javascript only functions create a new context -closure.
    • Every definition of a variable is really a declaration of the variable at the top of its scope and an assignment at the place where the definition is.

    var

    • function-scoped
    • hoist to the top of its function
    • redeclarations of the same name in the same scope are no-ops

    You may want to read MDN scope cheat sheet

    Due to hoisting You can even do things like this:

    function bar() {
        var x = "outer";
    
        function foo() {
            alert(x); // {undefined} Doesn't refer to the outerscope x
            // Due the the var hoising next:        
            x = 'inner';
            var x;
            alert(x); // inner
    
        }
        foo();
    }
    
    bar();​
    
    bar();​
    

    Demo

    So the foo function is converted to something like this:

    function foo() {
        var x;
        alert(x); // {undefined} Doesn't refer to the outerscope x
        // Due the the var hoising next:        
        x = 'inner';
        alert(x); // inner
    }​
    

    My question is: what is the scope of magicVar and is it okay to pass it into magicFunction as I've done?

    Define okay..., Yes the code is valid, but it's less readable then if the variables declarations were on the top, that's all.

提交回复
热议问题