在定义之前使用"[变量]".错误 [英] "[Variable] was used before it was defined" error
问题描述
我有几个这样的错误,我不确定如何正确地"解决它,问题是我有很多javascript文件(为了便于维护而分开使用),并且包括了插件等等.
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.
因此,在此示例中,我使用来自 http://www.openjs.com的快捷方式/scripts/events/keyboard_shortcuts/
So in this example I use shortcut which is from http://www.openjs.com/scripts/events/keyboard_shortcuts/
这只是定义
shortcut = {.......
然后,当我在代码中使用它时,
then when I in my code use it like
shortcut.add("F1", function () { showDialog(); }, { 'type': 'keydown', 'propagate': false, 'target': editor_document });
jslint会抱怨
JS Lint:快捷方式"在定义之前就已使用.
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
推荐答案
如果变量是由另一个文件定义的,则可以通过提供以下格式的注释来告诉JSLint:
If the variable is defined by another file, you can tell JSLint by providing a comment in the following format:
/*global shortcut*/
您可以通过用逗号分隔多个变量来执行此操作.追加:
和 true
或 false
(默认为 false
)将指定变量是否可以由当前变量重新分配.文件:
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*/
您缺少 var
关键字,该关键字用于为全局和函数作用域定义变量.
You're missing the var
keyword, which is used to define a variable for the global and function scopes.
var shortcut = { }
您需要对定义的每个变量使用 var
,否则会遇到很多问题.
You need to use var
for every variable defined, else you'll run into a mass of problems.
通过省略 var
关键字,可以 创建隐式全局变量,但对此却一无所知,根本不建议这样做.如果需要从内部范围创建全局变量,则可以将对象添加到 window
或根据上下文,将其添加到 this
:
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();
这篇关于在定义之前使用"[变量]".错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!