如果 JavaScript 是动态作用域,那么以下代码中最后的 console.log() 结果是什么?

If JavaScript is dynamic scoping, what would be the last console.log() result in the following code?

这就是我定义函数的方式,变量 x,y,z 是用某个整数定义的。

var a = 0;
var x = 1;
var y = 2;
var z = 3;

function f(n) {
    a = n;
}
function g(){
    console.log(a);
}
function h(){
    f(x); g();
}
function k() {
    var a = 0; g(); f(y);
}
f(z); g(); k(); g(); h(); g();

以下是我对上述代码是否动态作用域的看法:

f(z){
  a = z; // The value of a became z
}
g(){
  console.log(a); // Printing out the value of z
}
k(){
  var a = 0;
  g(){
    console.log(a); // Printing out 0
  }
  f(y){
    a = y; // Assign the value of y to the variable a initialized 5 lines above
  }
}
g(){
  console.log(a); // Printing out the value of z
}
h(){
  f(x){
    a = x;
  }
  g(){
    console.log(a) // Printing out the value of x
  }
}
g(){
  console.log(a) // Printing out value of z or x ??
}

不确定最后一个 console.log 会输出什么。

查看示例片段及其评论:

var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
    a = n;
}
function g(){
    console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
    f(x);  // a becomes 2 here since x = 2
    g();  // output var a value to console
}
function k() {
    var a = 0; // this sets a to 0 only in function scope
    console.log(`function scope value of var a is ${a}`);
    g(); // output var a value to console which is 1 here not 0
    f(y); // a becomes 4 here since y = 4
}
f(z); 
g(); 
k(); 
g(); 
h(); 
g();
console.log(`final value of var a is ${a}`);

下面的示例可以按您的意愿运行(如果我理解您的问题)。只需在函数 k() 中的 a 之前省略 var

var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
    a = n;
}
function g(){
    console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
    f(x);  // a becomes 2 here since x = 2
    g();  // output var a value to console
}
function k() {
    a = 0; // this sets a to 0 only in function scope
    console.log(`function scope value of var a is ${a}`);
    g(); // output var a value to console which is 1 here not 0
    f(y); // a becomes 4 here since y = 4
}
f(z); 
g(); 
k(); 
g(); 
h(); 
g();
console.log(`final value of var a is ${a}`);