Unused local variable warning in self-serving anonymous function

Eclipse generates a "Local variable never readable" when a variable is declared inside a self-signed anonymous function and not declared in the global scope.

Self-execution example:

var MODULE = {}; (function (module) { // THIS LINE GENERATES WARNING var FOO_BAR_ANON = {}; function Foo ( ) { if ( this instanceof Foo ) { // THIS IS WHERE VARIABLE IS USED this.fooBar = FOO_BAR_ANON; } else { return new Foo( ); } } module['Foo'] = Foo; })( MODULE ); 

Example global scope, warning not generated:

 var MODULE = {}; var FOO_BAR_GLOBAL = {}; function FooGlobal ( ) { if ( this instanceof FooGlobal ) { this.fooBar = FOO_BAR_GLOBAL; } else { return new FooGlobal( ); } } MODULE['FooGlobal'] = FooGlobal; 

Could you explain why the warning comes first and how to silence it?

+4
source share
2 answers

This seems to be a known bug in Eclipse:

https://bugs.eclipse.org/bugs/show_bug.cgi?id=351470

FOO_BAR_ANON captured when defining the function Foo inside an anonymous function and the link FOO_BAR_ANON inside Foo. See the Closures documentation.

Here is an example used in the error report (at the end of the page):

 (function() { var moveCaretTimer = -1; function setMask() { (function() { function focusEvent() { var moveCaret = function() { // empty }; clearTimeout(moveCaretTimer); moveCaretTimer = setTimeout(moveCaret, 0); } })(); } setMask.storageKey = storageKey; })(); 

moveCaretTimer marked as never read, its occurrences are not selected.

+3
source

If I remember my Javascript correctly, the reason it works in Global is because in your self-executing example, the variable FOO_BAR_ANON is outside the scope of Foo. When I included my JS validator in Eclipse RSA, your line

this.fooBar = FOO_BAR_GLOBAL;

cannot resolve the value, because with respect to foo the variable does not exist within its scope.

Also, to suppress this, my options for Javascript were as follows: Project-> Properties-> JavaScript-> Validation-> Errors and Warnings.

Here you can configure which alerts are issued or ignored. Your version of Eclipse may be different.

0
source

Source: https://habr.com/ru/post/1490969/


All Articles