Why is JSLint complaining about the global variable undefined / implied?

I am trying to understand why JSLint complains about an implied global variable in the following example:

var TEST = (function () { var count = 0; function get_count() { return add_one(); } function add_one() { count += 1; return count; } return { get_count: get_count }; }()); 

Running this through JSLint gives an error:

Problem with line 5 character: "add_one" is undefined.

Also saying:

Estimated Global: add_one 5

If you move the add_one() function to the get_count() function, the error disappears. However, with code like the one above, it does not cause errors when launched in the browser. Can anyone explain why JSLint is complaining?

Thanks!
Matt

+4
source share
3 answers

This is because JSLint uses Pratt Parser , a top-down parser, a hollow JavaScript interpreter. If this were truly interpreted, this would not have given you this error.

add_one is an implied global because the parser has not yet encountered this variable, so it assumes that your surrounding code will have this variable. But, if you flip it, then the parser has already stumbled on the add_one variable, and all the peaches and cream add_one

By the way, I noticed a small typo in your closing function line: }()); must be })(); .

+11
source

I am changing the order in which methods are declared that will solve your problem. As mentioned in another answer, some JavaScript analyzes use a top-down approach to read code, similar to how the C programming language does it. Modern translators and compilers use a 2-pass approach. The first pass is reading / compiling methods into memory. If he encounters any method calls that he does not know about, he will look at the entire set of methods in memory to determine if he exists. I would recommend setting the order because, although this may not cause problems, it would rather load this method into memory with the change.

 var TEST = (function () { var count = 0; function add_one() { count += 1; return count; } function get_count() { return add_one(); } return { get_count: get_count }; }()); 
+1
source

You get * add_one not defined * because JSLint believes that function expressions should be declared in the correct order for another problem ("* Implied global: add_one 5 *"), are you enough to add a comment such as / * globals add_one * / at the top of your script

+1
source

All Articles