gpt4 book ai didi

javascript - 引用全局变量时的奇怪行为。这是javascript中的错误吗?当然不是!

转载 作者:行者123 更新时间:2023-12-03 10:04:33 24 4
gpt4 key购买 nike

考虑以下代码。

<html>
<body>
<script>
var x = 5; //globally declared
function showX()
{
alert("x="+x); //trying to display global value

var x=10; //trying to create and initialize a local x
}
</script>
<input type = "button" value="Show X" onclick="showX()">
</body>
</html>

警报语句显示“x=undefined”。并且不会按预期打印 x 的全局值。等效的 Java 代码将显示 5!那么,这是一个错误吗?如果不是,那么如何解释这种行为?

最佳答案

ECMAScript Specification在第 12.2 节中说:

If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in s10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in 10.1.3) using property attributes { DontDelete}. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

所以这不是错误 - 局部变量是在输入函数时创建的。

关于javascript - 引用全局变量时的奇怪行为。这是javascript中的错误吗?当然不是!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/585725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com