Js scope function call

function A(){
    var a=1;
    var d=2;
    B(d);

}
function B(d){
    console.log(a);
}
A() //Error a is undefined

the scope of the execution of the js function has been a little unclear.
I would like to ask, like the above code, because the B function is called inside function A, then the whole scope chain should be B-A-window? So if I"m looking for a, after I can"t find an at the top of the scope chain (that is, B), why not find it in A? it seems to be directly in the global environment, right?
could you please tell me if there is any other solution besides passing a parameter in? thank you ~

Mar.25,2021
The scope of

js is lexical scope. No matter where or how a function is called, its lexical scope is determined only by where the function is declared.
if B is defined in A, B can read a.


does not depend on the case of the call, but on how it is defined.
if you define the scope chain of function B in function A, it is B-A-window .


in the block-level scope, the function declaration statement behaves like let, is not referenced outside the block-level scope. It would be nice to define function B in function A. For more information on scope, please see the scope


this is the specification.
in your example, an is not accessible in B anyway, and

function B(d){ // dAd
    console.log("a");
}
function A(){
    var a=1;
    var d=2;
    B(d);// BdAdBAa

}

you take it for granted that the variable query path such as B-A-window when called in B is taken for granted. In fact, for B, there is only B-window . The parameters passed by the entry are another matter and are not absolutely related to the variable query path.

The scope of the

function is determined when the function is defined, the definition of B is in the global environment, and the scope of B is the global scope.

Menu