One var per function in JavaScript?

后端 未结 4 604
轮回少年
轮回少年 2020-12-04 10:37

I\'ve been using JSLint to make me feel bad about my JavaScript. It is great, by the way. There is one check that I don\'t quite understand and I\'d like your views, please.

4条回答
  •  醉话见心
    2020-12-04 11:29

    Basically in JavaScript blocks ({ ... }) do not introduce a new scope, there is only function-scope, so no scope is created on any other statement.

    A variable introduced anywhere in a function is visible everywhere in the function.

    For example:

    function myFunction(){
      var one = 1;
    
      if (one){
        var two = one + 1;
      }
    
      (function () {
        var three = one + two;
      })();
    
      // at this point both variables *one* and *two* are accessible but 
      // the variable *three* was declared in the scope of a inner function
      // and is not accessible  at this point.
    }
    

    In languages with block scope, it recommended to declare the variables at the point of first use, but since JavaScript does not have block scope, it is better to declare all of a function's variables at the top of the function.

    Check this article.

提交回复
热议问题