Function was used before it was defined - JSLint

五迷三道 提交于 2019-11-30 17:56:38

If your code is well-written and object-oriented, it is possible to declare your functions before they are used. But JSLint sets a lot of standards that really have little relevance to the functionality of your application, and I really doubt there are any performance implications declaring functions one way or the other.

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)

In C it is what we call forward declaration, looks like it could be the same in JSLint. JSLint is aware of b and at that point b could be a function for all it cares (but if it isn't a function, it would throw an error of course)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!