繁体   English   中英

JavaScript函数范围和参数

[英]Javascript function scope and parameter

这是代码:

function b() {
  console.log(x);
};
function a() {
  var x= 1;
  b();
}
a();
//the output is : x is not defined!

有人可以帮助解释为什么输出不确定吗? 我认为它会输出1。为什么函数b()无法获得变量x?

您必须将x变量作为参数传递:

function b(x) {
  console.log(x);
};
function a() {
 var x= 1;
 b(x);
}
a();

您将闭包与实际调用函数混为一谈。 如果你有function b内部function a ,那么你就可以访问x像这样。

function a() {
   var x= 1;
   function b() {
      console.log(x); // print out 1
   };
   b();
}

如果 function 内部定义了var ,则该var只能在函数内使用。 如果varfunction 外部定义,则可以在任何地方使用它。 您的var x =1 function a()定义的,因此只能 function a() 要解决您的代码,只需将var x= 1移动 function a() 这是代码:

function b() {
    console.log(x);
}
var x= 1;
function a() {
    b();
}

或者,我建议您改用它。 它要短得多:

var x= 1
function b() {
    console.log(x);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM