问题
I have several of these errors and I am not sure how to "properly" solve it, the thing is that I have many javascript files (Seperated for easier maintainability) and I include plugins et cetera.
So in this example I use shortcut which is from http://www.openjs.com/scripts/events/keyboard_shortcuts/
This just defines shortcut to
shortcut = {.......
then when I in my code use it like
shortcut.add("F1", function () { showDialog(); }, { 'type': 'keydown', 'propagate': false, 'target': editor_document });
jslint will complain that
JS Lint: 'shortcut' was used before it was defined.
I also have my own code where I use functions declared in other files, so what is the "right" way to solve this
回答1:
If the variable is defined by another file, you can tell JSLint by providing a comment in the following format:
/*global shortcut*/
You can do this for a number of variables by comma separating them. Appending :
and true
or false
(defaults to false
) will specify whether the variable can be reassigned by the current file:
/*global shortcut:false, otherVar:true*/
You're missing the var
keyword, which is used to define a variable for the global and function scopes.
var shortcut = { }
You need to use var
for every variable defined, else you'll run into a mass of problems.
It is possible to create implicit globals by omitting the var
keyword, but it's highly frowned upon and not at all recommended. If you need to create a global variable from an inner scope, you can add the object to window
or, depending on the context, this
:
function defineShortcut() {
window.shortcut = {};
/* or this.shortcut = {}; */
}
defineShortcut();
回答2:
you must declare a variable shortcut with var keyword before using it, or else it will be a global variable which are considered (and are in fact) evil.
var shortcut;
shortcut = { ...
来源:https://stackoverflow.com/questions/8134049/variable-was-used-before-it-was-defined-error