The benefits of declaring variables at the top of the function body in JavaScript

后端 未结 4 804
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 17:43

I am reading Douglas Crockford\'s book \"Javascript: The Good Parts\". He is talking about scope and saying that JS doesn\'t have block scope:

In many mod

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 18:23

    That's not always a good idea. It depends what you're doing. What they mean when they say it's not necessary to declare "top level" variables, is that it doesn't matter. It can matter inside a function. Consider the following examples:

    varOne = 1; varTwo = 2; varThree = 3; // undeclared
    function lameFunc(){
      var varOne = 'Something'; // does no affect varOne at the top level
      return varOne;
    }
    

    Same as:

    var varOne = 1, varTwo = 2, varThree = 3; // declared
    function lameFunc(){
      var varOne = 'Something'; // does no affect varOne at the top level
      return varOne;
    }
    

    Of course, it's easier to see the variables with the keyword var and since there are no adverse effects at the "top level", it is recommended.

    Notice that, when I change lameFunc() you affect the higher lever var, either way.

    function lameFunc(){
      /* varOne is effected at the higher level whether or not `var` is declared
        above as in `varOne = 1` or `var varOne = 1` */
      varOne = 'Something';
      return varOne;
    }
    

    Additionally, if you declare a variable outside of event like var someInputVal = document.getElementById('someInput').value;, then lets say you want to get the value onclick of an Element. You would want the var declared within the Element.onclick = function(){/* in here */} because the input may have changed before you clicked on Element. It may be okay to declare var someInput = document.getElementById('someInput'); outside of the function that handles your Event, if the Element doesn't become undefined then you can access the like:

    var doc = document, bod = doc.body;
    function E(e){
      return doc.getElementById(e);
    }
    var someInput = E('someInput'), someInputVal = someInput.value;
    E('clickButton').onclick = function(){
      console.log(someInputVal); // will not be what document.getElementById('someInput').value is if it was changed before clicking
      var declared = someInput.value;
      console.log(declared);
    }
    

提交回复
热议问题