Javascript scoping of variables

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

    In javaScript, there is nothing called block level scope. It is treated same as global variable. Now let's analyze these statements and their scope. Initially, you have declared var x = 5;. Then you have defined two functions and then again you have defined var x = 10;. Please note that JavaScript will override the value of x. Now x is 10 globally.

    Now you have declared z = g(f); You are passing a function as a parameter. Inside g, you have declared x again as var x = 7;. Please note that the variable defined inside a function has the higher preference than the same variable name declared in the global scope and also the current value of the variable is visible only to this function. Outside g, everyone knows that x is 10.But inside g, value of x will be 7.

    Now, you have returned h(x); this means you are calling f(y) as f(7); f still knows that x is 10 globally and doesn't have any idea whether it even existed inside function g. So f computes (10 + 7) - 2. Hence the value of z becomes 15.

    For clarification, I would recommend you to use the debugger present in the browser tools. Debug each line and understand how the scope works. Hope it helps.

提交回复
热议问题