javascript 覆盖javascript函数中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22356757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:59:35  来源:igfitidea点击:

override variable in javascript function

javascriptvariablesscope

提问by elevenMinutes

Firstly I want to say that I was searching some information about scope variables in javascript (e.g What is the scope of variables in JavaScript?) and I was trying to understand why my code behaves like that but finally I really don't know. I can't override var a in my function in function, I can do this only using a = 6;without var. Why a is undefined before if statement and overriding this variable ? Why there is no result like this:

首先,我想说我在 javascript 中搜索有关范围变量的一些信息(例如JavaScript 中变量的范围是什么?),我试图理解为什么我的代码会这样,但最后我真的不知道。我不能在我的函数中覆盖 var a,我只能在a = 6;没有 var 的情况下使用它。为什么 a 在 if 语句之前未定义并覆盖此变量?为什么没有这样的结果:

5

equal 5
equal 6

5

等于 5
等于 6

I have something like this instead:

我有这样的事情:

undefined

not equal 5
equal 6

不明确的

不等于 5
等于 6

Here's my code:

这是我的代码:

    var a = 5;

function something(){
    console.log(a);
    if(a == 5){
        console.log('equal 5')
    }
    else{
        console.log('not equal 5');
    }    
   var a = 6;

    function test(){
        if(a == 6){
        console.log('equal 6');
    }
    else{
        console.log('not equal 6')
    }
    }    
    test();    
}
something();

回答by xdazz

This is because javascript variable hoisting.

这是因为 javascript 变量提升。

Your code is equal to:

您的代码等于:

var a = 5;

function something(){
    var a;  // here
    console.log(a); // a is the local variable which is undefined
    if(a == 5){
        console.log('equal 5')
    }
    else{
        console.log('not equal 5'); // a is undefined so not equal 5
    }    

    a = 6; // a is assigned to 6

    function test(){
        if(a == 6){
            console.log('equal 6');  // a is 6 here
        }
        else{
            console.log('not equal 6')
        }
    }    
    test();    
}
something();

回答by cerpintaxt

Because when you declare var a = 6the second time you are overriding the first declaration of a, i.e. var a = 5. So when you define the function something(), ahas not yet been defined, hence console.log(a)returns undefined.

因为当您var a = 6第二次声明时,您将覆盖a,即的第一次声明var a = 5。因此,当您定义函数时something()a尚未定义,因此console.log(a)返回未定义。

However when you replace the second declaration of awith just a = 6the first declaration remains valid, you just change the value of aafterwards and so you get the expected result:

但是,当您a仅用a = 6第一个声明替换第二个声明时仍然有效,您只需更改 after 的值即可a获得预期结果:

5 
equal 5
equal 6 

See this postfor more discussion.

有关更多讨论,请参阅此帖子