JSLint: 在定义错误之前使用函数

我使用 JSLint 来验证我的大多数外部 Javascript 文件,但是我收到的最大数量的错误来自于函数在定义之前被使用的情况。

这真的是我应该担心的问题吗?

似乎 Firefox,IE7和 Chrome 都不在乎。根据 JSLint 的说法,像流行的 init()(我经常使用)这样的函数通常会粘在文件的顶部,因为这对我来说是有意义的(我喜欢假装它类似于 main()) ,需要被推到文件的底部。

46199 次浏览

If you declare functions using the function keyword, you can use them before they're declared. However, if you declare a function via another method (such as using a function expression or the Function constructor), you have to declare the function before you use it. See this page on the Mozilla Developer Network for more information.

Assuming you declare all your functions with the function keyword, I think it becomes a programming-style question. Personally, I prefer to structure my functions in a way that seems logical and makes the code as readable as possible. For example, like you, I'd put an init function at the top, because it's where everything starts from.

As this is the top rated google hit and other people might not be seeing it at first in the jslint tool, there is a option called "Tolerate misordered definitions" that allows you to hide this type of error.

/*jslint latedef:false*/

From jslint's website (http://www.jslint.com/lint.html), you can read about a /*global*/ directive that allows you to set variables that are assumed to be declared elsewhere.

Here is an example (put this at the top of the file):

/*global var1,var2,var3,var4,var5*/

The :true :false is not actually needed from my experience, but it looks like it's recommended from what I read on the site.

Make sure the initial global statement is on the same line as /*, or else it breaks.

You can always declare the offending function at the top

var init;

.... but then you'll have to remove the "var" when you get to the true definition further down:

init = function() { };

If you're using jshint you can set latedef to nofunc, which will ignore late function definitions only.

Documentation - http://www.jshint.com/docs/options/#latedef

Example usage:

/* jshint latedef:nofunc */


noop();


function noop() {}

Hope this helps.

To disable this warning in jshint for all files, place this in your .jshintrc file:

{
"latedef": false
}

it is very unfortunate the latedef option was removed. This is essential when trying to create a 'class' with an interface at the top, ie,

function SomeClass() {
var self = this;
self.func = func;


function func {
...
}
}

This style is very common but does not pass jsLint because func is 'used' before being defined. Having to use global for each 'member' function is a total pain.

In your .jshintrc file, set:

  "latedef": "nofunc",