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!
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,ContainerAandContainerBeven 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.
jQueryis the only global object for jQuery library and its plugins,ContainerAis the only global object for LibraryA,ContainerBis 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.Xinto your code. Instead, your code is instantiating classes from theaspNetcontainer (that at the moment happens to be a synonym forwindow, but that might change in the future). Also, havingaspNet.Xin 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.