Resharper, Javascript: "Use of implicitly declared global variable 'X'"

rythos42 picture rythos42 · Sep 30, 2011 · Viewed 25.1k times · Source

I'm using Resharper 6 and ASP.NET Web Methods and have an irritating warning in my Javascript files:

"Use of implicitly declared global variable 'X'"

The reason is that the web method is created in Javascript as:

new X.example().webMethod(arg1, arg2, successCallback, failureCallback);

And X...is implicitly defined. I'm wondering if there is a solution to explicitly define this? It's defined in some auto-generated JS file, created by the ASP.NET web method framework stuff.

My question is: how do I get rid of the error for this situation, without getting rid of it for legitimately wrong situations?

Thanks!

Answer

Milan Gardian picture Milan Gardian · Nov 15, 2011

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:

multiple containers

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:

window as a container

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.