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

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

问题描述

在下面的代码中:

  var greeting =hi; 

函数changeGreeting(){
if(greeting ==hi){
var greeting =hello;
}

警报(问候语);


changeGreeting();

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

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

警报(问候语);
}

...按预期收到hello。



我不会在代码中重新声明这样的变量,但为什么会发生这种情况? JavaScript变量具有函数范围。因此,函数内部存在 var greeting 会声明一个本地的 greeting 变量,这个变量在在中提及它的时间如果条件:全局变量在函数内部不可见,被本地函数遮蔽。因此,如果 if 没有发生,那么对 hello 的赋值就不会发生,变量仍然是未定义的。 / p>

在第二个示例中,您始终使用全局变量,但不会被局部变量掩盖(因为没有 var greeting

code>在函数中),并且事情按照您的预期工作。


In the following code:

var greeting = "hi";

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

    alert(greeting);
}

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 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.

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天全站免登陆