重新声明JavaScript变量有什么目的吗? [英] Is there any purpose to redeclaring JavaScript variables?

查看:183
本文介绍了重新声明JavaScript变量有什么目的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript新手。

I am new to JavaScript.

<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>

结果是:

5
5

x 是第二次声明它应该是未定义的,但它保留了以前的值。请解释此重新声明是否有任何特殊目的。

When x is declared the second time it should be undefined, but it keeps the previous value. Please explain whether this redeclaration has any special purpose.

推荐答案

您并未真正重新声明该变量。

You aren't really re-declaring the variable.

JavaScript中的变量语句需要提升,这意味着它们在分析时以及稍后在运行时中进行评估分配完成。

The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.

您的代码在解析阶段结束时,在执行之前看起来像这样:

Your code at the end of the parse phase, before the execution looks something like this:

var x;
x = 5;

document.write(x);
document.write("<br />");
document.write(x);

这篇关于重新声明JavaScript变量有什么目的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆