Redeclare JavaScript Variable

前端 未结 3 508
一生所求
一生所求 2020-12-17 00:05

In the following code:

var greeting = \"hi\";

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

    alert(g         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-17 00:53

    It's very simple: JS hoist the Variable declarations to the top of the current scope, but any operations (including assignments) aren't hoisted (within the same scope, see second case explanation), of course. So your snippet is translated to

    (function()
    {
        var currentSize;//undefined
        if (currentSize == 'hi')//always false
        {
            currentSize = 'hello';//assignment that will never be
        }
        alert(currentSize);//alerts undefined, of course
    }());
    

    By leaving out the var, proceeds to scope scanning (checking for the variable being declared in the global scope). Sadly, in doing so, the context of the first use of the var is lost (inside a branch), and the assignment is hoisted, too. An implied global is translated to:
    Thank god this isn't true. I assumed it was, because I tested a couple of things in the console that seemed to corroborate this. In this case @amadan is right: you're using the global variable (called greeting in your snippet by mistake when I posted this). I'm going to leave the code below (corrected it) to show what implied globals actually are, hoping it helps somebody sometime in understanding scopes/scope-scanning in JS.

    var currentSize = 'hello';
    //well, actually implied globals can be deleted, so it's more like
    Object.defineProperty(this,'currentSize',{value:undefined,
                                              writable:true,
                                              enumerable:true,
                                              configurable:true});
    (function()
    {
        if (currentSize == 'hi')//always false
        {//this still doesn't get executed
            currentSize = 'hello';//assignment that will never be
        }
        alert(currentSize);//alerts undefined
    }());
    

提交回复
热议问题