user1134179 user1134179 - 1 year ago 116
Javascript Question

JSLint Out of Scope

I have the following code and am getting 'myGlobal' used out of scope. I have to return myGlobal or a new object because the object is added onto in other files.

var myGlobal= (function (my) {
'use strict';

return my;
}(myGlobal|| {}));


Is there a way to satisfy jsLint in this case?

Answer Source

When I bump into this, I think I usually cheat. In a browser context, for instance, all the global variables are really living on the window object, so you can do something like this:

/*jslint sloppy:true, white:true, browser:true */
window.myGlobal = (function (my) {
    'use strict';

    return my;
}(window.myGlobal|| {}));

That logically reduces to the same thing, and makes JSLint happy.

Quick edit: Alternately, though this is essentially the same trick all over again (and this sounds like it's potentially what you're already trying to set up with myGlobal), consider grouping your globals into namespaces that you define as global, like this...

/*jslint sloppy:true, white:true, browser:true */
/*global MyNamespace */
MyNamespace.myGlobal = (function (my) {
    'use strict';

    return my;
}(MyNamespace.myGlobal|| {}));

Though that's kind of a similar situation. If you can't be absolutely sure you have an include defining MyNamespace somewhere earlier, you're in the same boat you're in now trying to check for MyNamespace's existence.

So the quick answer reduces right back to the window trick, above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download