Is there any purpose to redeclaring JavaScript variables?

前端 未结 9 1769
傲寒
傲寒 2020-12-11 18:38

I am new to JavaScript.





        
相关标签:
9条回答
  • 2020-12-11 19:13

    so when the second time when its declared x should be undefined

    What part of the specification says this?

    "Undefined behaviour" does not mean "the variable will be undefined".

    0 讨论(0)
  • 2020-12-11 19:13

    I recently wrote code like:

    var obj1 = get_an_object();
    var v = obj1.get_velocity();
    v += changes_in_velocity();
    obj1.set_velocity(v);
    
    var obj2 = get_an_object();
    var v = obj2.get_velocity();
    v += changes_in_velocity();
    obj2.set_velocity(v);
    

    (The actual code was more complicated and less repetitive)

    So far as the browser is concerned, the second var v statement was redundant and pointless. To me, it served two purposes. It said to forget everything I knew about the old v, because this was a new usage. And it meant I could re-order the code, or comment out the first half, without breaking things.

    0 讨论(0)
  • 2020-12-11 19:15

    var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:

    var a= 0;
    
    function foo() {
        a= 1;
        return a;
        var a;
    }
    
    var b= foo();
    alert('global a='+a+', local a='+b);
    

    Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.

    So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:

    for (var i= 0; i<onething.length; i++) {
        ...do some trivial loop...
    }
    
    for (var i= 0; i<anotherthing.length; i++) {
        ...do another trivial loop...
    }
    

    Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.

    Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.

    0 讨论(0)
提交回复
热议问题