2011-04-10 118 views
1

我一直在寻找网络上的计算器代码,并且发现了类似下面的代码。为什么变量在Javascript中的函数之前声明

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

var getValues= ""; 

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

请亲切地帮我回答我的问题。

谢谢大家。

回答

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加载这个文本文件(文件://$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> 

结果是:NaNNot a Number

这就是关于JS的懒惰和宽容。你的问题当然也可以解释变量和功能的范围。但为此,已经有2个答案。当然,如果他们还不够,我也可以在这里编辑一个详细的解释。

+0

非常感谢你。我非常感谢你的帮助。再次感谢 – Muzammil 2011-04-10 15:26:12

2

他正在做的是他将变量移出函数的范围。

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

看到这个问题,以了解更多有关变量的作用域:What is the scope of variables in JavaScript?

+0

非常感谢。现在我正在阅读你给我的链接,这对我非常有帮助。 – Muzammil 2011-04-10 15:30:15

3

这样,它是一个全局变量,通过函数调用仍然存在的价值。 如果你把它放在函数内部,当函数被调用时它总是0

+1

当函数被调用时,getValues不会“始终为零”。它是一个全局变量,在函数被调用之前被赋值为''(空字符串)。如果函数被调用,它将具有该函数赋予它的任何值。所以它只会有一个零值,如果这是它被分配上次调用函数的值。 – RobG 2011-04-10 12:58:54

+0

我试图解释,如果*它在函数内*,那么它将始终为空,它将不会通过不同的调用保持其值,并且不能用于其他函数。 – AlfonsoML 2011-04-10 15:30:29

+0

@RobG'code'var getValues =“”; function updateField(val){ getValues + = val; document.calc.putValues.value = getValues; } 以及我也可以分配变量,如'code'var getValues;是不是没关系为什么我需要分配空 – Muzammil 2011-04-10 15:31:23

相关问题