Is there any purpose to redeclaring JavaScript variables?

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

I am new to JavaScript.





        
9条回答
  •  悲&欢浪女
    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.

提交回复
热议问题