Javascript scoping of variables

前端 未结 3 1602
-上瘾入骨i
-上瘾入骨i 2021-01-29 09:47

The output is 15 (in f, x is taken to be 10 and y is 7) with the following:

var x = 5;
function f(y) { return (x + y) - 2};
function g(h) { var x = 7; return h(x         


        
3条回答
  •  清酒与你
    2021-01-29 10:28

    var x = 5;
    function f(y) { return (x + y) - 2};
    function g(h) { var x = 7; return h(x) };
    { var x = 10; z = g(f); console.log(z) };
    

    is a bit of a mess, so let's clean it up:

    /*  1 */var x = 5;
    /*  2 */
    /*  3 */function f(y) {
    /*  4 */  return (x + y) - 2
    /*  5 */};
    /*  6 */
    /*  7 */function g(h) {
    /*  8 */  var x = 7;
    /*  9 */  return h(x)
    /* 10 */};
    /* 11 */
    /* 12 */{
    /* 13 */  var x = 10;
    /* 14 */  z = g(f);
    /* 15 */  console.log(z)
    /* 16 */};
    

    This still has a number of issues which I copied verbatim. All I did was add whitespace. Now I'm going to clean up the code so that it expresses the actual execution order.

    // variable and function declaration happens before assignment
    // variables are scoped to their containing function,
    // or, when no parent function exists, to global scope
    var x;
    
    function f(y) {
      // cleaned up semicolon usage (lines 4 & 5)
      // while JavaScript's automatic semicolon insertion would work
      // it's generally better to be explicit about intent
      return x + y - 2;
    }
    
    function g(h) {
      // again separated variable declaration from assignment
      // from line 8 above
      var x;
      x = 7;
      return h(x);
    }
    
    // removed unnecessary block scope from lines 12 & 16
    
    // variable assignment now can happen after declaration
    // x is assigned from line 1 above
    x = 5;
    
    // x is subsequently overwritten from line 13 above as
    // JS variables don't have block scope
    // duplicate var declaration has no effect and is removed
    x = 10;
    
    z = g(f);
    
    console.log(z);
    

    Now that the code is properly formatted, it's immediately clear that x will have a value of 10 because the execution order leads to x being overwritten.

提交回复
热议问题