Contending with JS “used before defined” and Titanium Developer

后端 未结 1 734
醉酒成梦
醉酒成梦 2021-02-14 13:03

I have a lengthy JavaScript file that passes JSLint except for \"used before it was defined\" errors.

I used normal function declarations, as in...

funct         


        
1条回答
  •  粉色の甜心
    2021-02-14 13:49

    No, EM's answer is NOT the right solution. Try running this JavaScript:

    (function () {
       foo(); // right
    
       var foo = function () {
         console.log("wrong");
       };
    
       foo(); // wrong
    
       function foo() {
         console.log("right");
       }
    
       foo(); // wrong
    }());
    

    This is because the interpreter will first read the function declaration, create the name foo as a function that prints "right", then reads the var statement, and find that there is already a name foo so it will skip creating a new variable with the value undefined, as normally happens. Then it processes the code, line-by-line, which includes an assignment to foo. The function declaration does not get reprocessed. Maybe this will behave differently in Titanium, but try this in Firebug and you'll get what I got.

    A better solution is:

    var screen1, buildMenu;
    
    screen1 = function () { buildMenu(); };
    buildMenu = function () { screen1(); };
    

    This will also pass JSLint, and produce the correct behavior.

    0 讨论(0)
提交回复
热议问题