重新声明 JavaScript 变量 [英] Redeclare JavaScript Variable

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

问题描述

在以下代码中:

var greeting = "hi";

function changeGreeting() {
    if (greeting == "hi") {
        var greeting = "hello";
    }

    alert(greeting);
}

changeGreeting();​

...greeting 未定义.但是,如果我删除 var 并将 changeGreeting() 更改为:

...greeting is undefined. However if I remove the var and change changeGreeting() to this:

function changeGreeting() {
    if (greeting == "hi") {
        greeting = "hello";
    }

    alert(greeting);
}

...我按预期收到你好".

...I get "hello" as expected.

我永远不会在我的代码中重新声明这样的变量,但为什么会发生这种情况?

I would never redeclare a variable like this in my code, but why does this happen?

推荐答案

JavaScript 变量具有函数作用域.因此,函数内部 var greeting 的存在将声明一个本地 greeting 变量,在 if 中提到它时将是未定义的> 条件:全局变量在函数内部不可见,被局部变量掩盖.因此,if 不会发生,对 hello 的赋值不会发生,变量仍未定义.

JavaScript variables have function scope. Thus, the very presence of var greeting inside the function will declare a local greeting variable, which will be undefined at the time of its mention in if condition: the global variable will not be visible inside the function, being overshadowed by the local one. Therefore, the if does not happen, the assignment to hello doesn't happen, the variable is still undefined.

在第二个示例中,您始终使用全局变量,它没有被局部变量所掩盖(因为函数内部没有 var greeting),并且一切都如您所愿.

In the second example, you're using the global variable throughout, it is not overshadowed by a local variable (because, no var greeting inside the function), and things work as you expect.

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

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