One var per function in JavaScript?

后端 未结 4 600
轮回少年
轮回少年 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:33

    The lack of block scope explains the code below:

    var a = 1;
    if (something) {
        var a = 2;
    }
    
    alert(a); // Alerts "2"
    

    In most C-style (as in syntax) languages, the var a = 2 definition would define 'a' only for the scope of the if block. Using a single var statement at the top of the function helps to avoid this quirk of Javascript, which is not always as obvious as the above, and would be unexpected to C/C#/Java programmers.

提交回复
热议问题