Resharper, Javascript: "Use of implicitly declared global variable 'X'"
When using symbols (functions, constants, global variables) defined in other JavaScript files, I pass them to the current file's "scoping function" (top-level, usually anonymous, function that prevents global namespace pollution) as parameters:
As you can see from the screenshot, ReSharper (6.0.2202.688) is happy with jQuery
, ContainerA
and ContainerB
even though they are not defined anywhere in the current file. The comment in line 1 is only there for JSLint (no errors).
This technique assumes that all the other JavaScript files follow the JavaScript best practice of minimally polluting the global namespace by defining a single top-level object that contains all the exported (public) symbols (i.e. jQuery
is the only global object for jQuery library and its plugins, ContainerA
is the only global object for LibraryA, ContainerB
is the only global object for LibraryB, etc).
Because you clearly don't have control over ASP.NET Web Methods generating constructor functions into global namespace, in your case you have to resort to the ultimate container, window
:
This is a slight variation on the technique suggested by @sethobrien in his comment. An important (IMHO) advantage is that you're not hard-coding window.X
into your code. Instead, your code is instantiating classes from the aspNet
container (that at the moment happens to be a synonym for window
, but that might change in the future). Also, having aspNet.X
in the code declares your intention more clearly for people who will read your code in the future. Finally, local variables can be shortened by JavaScript minimizers yielding slightly smaller file transmitted to client browsers.
Adding following to the top of your script file ///<reference path="my.js" />
(my.js is the file where X is defined) will likely fix this warning since ReSharper start seeing this global variable.
Otherwise to minimize changes you can add var X = window.X;
near the top of the file. Try to make it not to polute global namespace and make sure it will not confuse code that actually instantiates X on the window.
Got exactly the same problem after moving Jasmine to an external Bower package and excluding Jasmine's code from VS project. Resharper immediately started complaining on Use of an implicitly declared global variable 'describe'
and so on.
I solved this by adding to the project another file named workaround.js
dummy definitions for the variables. In your case it would be:
// This is a workaround for R# complaining on undefined global variables.
// In practice they come from and are defined by external frameworks, so
// this is not a real issue.
var X = function () { };
And this is a file in my project - https://gist.github.com/barahilia/62871d9219cee825d82e.
If it is an error that can be ignored you can use
// ReSharper disable once UseOfImplicitGlobalInFunctionScope