Javascript scoping of variables

前端 未结 3 1638
-上瘾入骨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:25

    vars are not blocked scoped, so the last line is equivalent to

    x = 10; z = g(f); console.log(z)
    

    It should be clearer now that the value of x was changed to 10 before f was executed.
    It is also important to note that free variables are evaluated when a function is called, not when it was defined. And of course the value of a variable can change between the definition of a function and the call of the function, just like in your example.

    In the third line, x is local to g and therefore is completely independent from the "outer" variable x.

    See also What is the scope of variables in JavaScript?


    A much simpler example that demonstrates this behavior would be:

    var x = 5;
    function foo() {
      console.log(x);
    }
    x = 10;
    foo(); // outputs 10
    

提交回复
热议问题