Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Use this as the context for the global scope:

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

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

The same can be done for browser host objects, such as document:

var controller = {};

this.model = {"view": this.document || NaN, "viewmodel": controller.foo };


controller.foo = function myfoo(model) {
    'use strict';
    return model.document.title;
};

this.model.viewmodel(this.model);

References

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top