问题
I get the following error in jsLint:
'document' was used before it was defined.
Line that causes the error:
document.cookie = name + "=" + value + expires + "; path=/";
I get why this happens, but I would like my code to be compliant.
How do I resolve this?
Thanks.
回答1:
Place
/*jslint browser:true */
in the beginning of the body of your function. Or, alternatively, you may use
/*global document: false */
JSLint is for the checking of any javascript code, and the document
global object does not exists everywhere, so you have to manually tell JSLint that your code is aimed to be executed in browser, and thus document
global variable is defined. For example, for server-side javascript it is expected for JSLint to report about this error.
回答2:
From jslint's website, 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\*/
or, in starjava's case:
/\*global document\*/
I'm not actually sure if the :true
or :false
is needed, but it looks like it's recommended from what I read on the site. http://www.jslint.com/lint.html
Make sure the initial global statement is on the same line as '/\*'
, or else it breaks.
回答3:
if you are using node can add the following line
/ * node JSLint: true * /
at the start of the script http://jslinterrors.com/a-was-used-before-it-was-defined/
回答4:
If all your JS code is supposed to be run from browser then just the add the --browser
flag.
jslint --browser my.js
回答5:
In cli mode you can use config file:
jslint.conf
{
"predef": [
"module",
"require",
"window",
"document",
"jQuery",
"Backbone",
"Marionette",
"Modernizr",
"_",
"setTimeout",
"clearTimeout",
"setInterval",
"clearInterval"
],
"evil":false,
"indent":4,
"vars":true,
"passfail":false,
"plusplus":false
}
And use jslint with --config jslint.conf
parameter.
来源:https://stackoverflow.com/questions/10766201/how-to-rectify-document-was-used-before-it-was-defined-using-jslint