One var per function in JavaScript?

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

    The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.

    so if you have a function like this

    var i = 5;
    function testvar () {
         alert(i);
         var i=3;
    }
    testvar();
    

    the alert window will contain undefined. because internally, it's been changed into this:

    var i = 5;
    function testvar () {
         var i;
         alert(i);
         i=3;
    }
    testvar();
    

    this is called "hoisting". The reason crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur.

提交回复
热议问题