为什么 JavaScript 中变量要在函数之前声明
我在网上寻找计算器代码,发现了如下代码。
但我心里有一个问题。为什么程序员要在创建函数之前声明变量?
var getValues= "";
function updateField(val) {
getValues += val;
document.calc.putValues.value = getValues;
}
请帮我回答我的问题。
谢谢大家。
I was looking for calculator codes on net and I discovered code like the following.
But i have a question in my mind. Why did the programmer declare the variable before creating the function?
var getValues= "";
function updateField(val) {
getValues += val;
document.calc.putValues.value = getValues;
}
Please kindly help me answer my question.
Thank you all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样,它就是一个全局变量,可以通过函数调用保留其值。
如果你把它放在函数内部,当函数被调用时它总是0
That way it's a global variable that persists its value through the function calls.
If you put it inside the function it will be always 0 when the function is called
他所做的是将变量移出函数的范围。
这将使同一变量可以通过同一范围内的其他方法访问。
请参阅此问题以了解有关变量作用域的更多信息:JavaScript 中变量的作用域是什么?
What he's doing is he's moving the variable out of the scope of the function.
This will make the same variable accessible by other methods in the same scope.
See this question to learn more about variable scope : What is the scope of variables in JavaScript?
要知道,变量其实是可以在函数下声明的。但它必须在使用之前声明,即在调用函数之前声明。
我创建了一个测试场景来展示我的意思。
我创建了一个名为
test.html
的文本文件,其中包含以下简单内容:如果我在 Firefox4 中加载此文本文件(文件://$path_to_file/test.html),我会收到一个警告框,其中包含消息
你好世界
。然后我改变了顺序:
结果是一样的:
Hello World
但是当我将声明放在这样的调用下时:
我得到了不同的结果:
undefined world
。 JavaScript 认识到它不知道a
可能是什么,因此将其处理为undefined
。当然,数字之和可能与字符串之和的解释不同,所以我也测试了这一点:
结果是:
NaN
意思是不是数字
。这就是JS的懒惰和宽容。您的问题当然也可以解释为关于变量和函数的范围。但对此已经有两个答案。当然,如果还不够的话我也可以在这里编辑详细的解释。
You know, the variable can actually be declared under the function. But it must be declared before it is used, meaning before the function is called.
I created a test scenario to show what I mean.
I created a textfile called
test.html
with the following simple content:If I load this text file in my Firefox4 (with file://$path_to_file/test.html) I get an alert box with the message
Hello world
.Then I changed the order:
The result was the same:
Hello World
But when I was putting the declaration under the call like this:
I got a different result:
undefined world
. JavaScript recognizes that it doesn't know whata
could be and so handles it asundefined
.Of course a sum of numbers could have been interpreted differently from a sum of strings, so I also tested this:
The result was:
NaN
meaningNot a Number
.That is all about laziness and tolerance of JS. Your question can of course also be interpreted concerning the scope of variables and functions. But for that there are already 2 answers. Of course, if they are not enough I can also edit a detailed explanation here.