Function was used before it was defined - JSLint

后端 未结 3 1230
一向
一向 2021-01-04 08:58

JSLint does not like this code saying \"\'b\' was used before it was defined\"

var a = function () {
        b();
    },

    b = function () {
        alert         


        
3条回答
  •  [愿得一人]
    2021-01-04 09:28

    So why is JSLint doing this? Is there a reason I should be declaring all my functions first?

    Yes, otherwise there might be some unexpected errors. Your code works because of JavaScript's "Hoisting". This mechanism pulls up all declarations, implicit or explicit and can cause some unexpected results.

    Consider this code:

    var s = "hello";    // global variable
    function foo() {
        document.write(s);   // writes "undefined" - not "hello"
        var s = "test";      // initialize 's'
        document.write(s);   // writes "test"
    };
    foo();
    

    It's being interpreted as follows:

    var s = "hello";    // global variable
    function foo() {
        var s;               // Hoisting of s, the globally defined s gets hidden
        document.write(s);   // writes "undefined" - now you see why
        s = "test";          // assignment
        document.write(s);   // writes "test"
    }
    foo();
    

    (example taken from the german Wikipedia page: http://de.wikipedia.org/wiki/Hoisting)

提交回复
热议问题