3

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?

user1134179
  • 539
  • 1
  • 12
  • 24
  • 1
    [Tell JSLint to ignore the code?](http://stackoverflow.com/questions/599859/jslint-control-comments-selective-ignore) – Robert Harvey Feb 02 '14 at 07:00
  • Could declare and set separately: `var myGlobal; myGlobal = ((...)(myGlobal || {}));` – Jonathan Lonowski Feb 02 '14 at 07:08
  • @JonathanLonowski: Isnt that just equivalent to `var myGlobal; myGlobal = ((...)({}));` ? – hugomg Feb 02 '14 at 07:19
  • You can't use `myGlobal` during the assignment to it. You can only use it AFTER the assignment is done which in your case means after the expression on the right is fully done being evaluated and then assigned to `myGlobal`. – jfriend00 Feb 02 '14 at 07:51
  • @missingno No. The `myGlobal ||` still lets it reuse an existing object. The separate `var myGlobal;` just ensures that `myGlobal` is declared and is a no-op if it is, leaving the current value unaltered. – Jonathan Lonowski Feb 02 '14 at 08:28

2 Answers2

2

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.

ruffin
  • 16,507
  • 9
  • 88
  • 138
0

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

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265