最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "[Variable] was used before it was defined" error - Stack Overflow

programmeradmin4浏览0评论

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 /

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 plain 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

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./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 plain 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

Share Improve this question edited Mar 8, 2012 at 16:35 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Nov 15, 2011 at 9:22 Mech0zMech0z 3,6476 gold badges51 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

If the variable is defined by another file, you can tell JSLint by providing a ment in the following format:

/*global shortcut*/

You can do this for a number of variables by ma 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 remended. 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();

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 = { ...
发布评论

评论列表(0)

  1. 暂无评论