如果 JavaScript 是动态范围,那么下面代码中的最后一个 console.log() 结果是什么?

问题描述

这就是我定义函数的方式,变量 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}`);

下面的例子按你的意愿工作(如果我理解你的问题)。只需在函数 var 中省略 a 前的 k()

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}`);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...