“[Variable] was used before it was defined” error

旧城冷巷雨未停 提交于 2019-12-01 08:10:49

问题


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

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