为什么变量在Javascript中的函数之前声明

时间:2011-04-10 12:44:15

标签: javascript global-variables calculator

我在网上寻找计算机代码,我发现了如下代码。

但我脑子里有一个问题。为什么程序员在创建函数之前声明变量?

var getValues= "";

function updateField(val) {
    getValues += val;
    document.calc.putValues.value = getValues;
}

请帮助我回答我的问题。

谢谢大家。

3 个答案:

答案 0 :(得分:3)

这是一个全局变量,它通过函数调用来保持其值。 如果将其放在函数中,则在调用函数时它将始终为0

答案 1 :(得分:2)

他正在做的是将变量移出功能范围。

这将使相同范围内的其他方法可以访问相同的变量。

请参阅此问题以了解有关变量范围的更多信息:What is the scope of variables in JavaScript?

答案 2 :(得分:1)

你知道,变量实际上可以在函数下声明。但它必须在使用之前声明,这意味着在调用函数之前。

我创建了一个测试场景来展示我的意思。

我创建了一个名为test.html的文本文件,其中包含以下简单内容:

<script type="text/javascript">
var a = "hello"; // <- the declaration of the variable before the function
function b(){ // <- the actual function
  a += " world";
  alert(a);
}
b(); // <- and here it is called
</script>

如果我在Firefox4中加载此文本文件(使用file://$path_to_file/test.html),我会收到一个警告框,其中包含Hello world消息。

然后我改变了顺序:

<script type="text/javascript">
function b(){ // <- the actual function
  a += " world";
  alert(a);
}
var a = "hello"; // <- the declaration of the variable under the function
b(); // <- and here it is called
</script>

结果是一样的:Hello World 但当我把声明放在这样的电话中时:

<script type="text/javascript">
function b(){ // <- the actual function
  a += " world";
  alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>

我得到了不同的结果:undefined world。 JavaScript认识到它不知道a可能是什么,因此将其处理为undefined

当然,数字的总和可能与字符串之和的解释不同,所以我也对此进行了测试:

<script type="text/javascript">
function b(){ // <- the actual function
  a += 3;
  alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>

结果是:NaN表示Not a Number

这完全是关于JS的懒惰和宽容。您的问题当然也可以解释为变量和函数的范围。但就此而言,已有2个答案。当然,如果它们还不够,我也可以在这里编辑详细的解释。

相关问题