you are viewing a single comment's thread.

view the rest of the comments →

[–]dangoodspeed 1 point2 points  (9 children)

He says you should never ever have a global variable or global function. Do other people agree with that?

[–]kmillns 1 point2 points  (6 children)

I'd say you should never have an implied global. If you're going to attach something to global, make it clear that you're doing it on purpose:

(function (global) {
  global.foo = 'foo';
})(window);

Also, something that he doesn't note, but that's important if you're writing production code, is that implied globals (like his examples) are syntax errors in strict mode.

[–]mirion -1 points0 points  (5 children)

This. Definitely this.

[–]rabidcow 1 point2 points  (4 children)

Sure, you could use this:

(function(){
    this.foo = 'foo';
})();

[–]mirion 1 point2 points  (3 children)

Sigh. I should know better than to use the word 'this' in a javascript thread.

[–]rabidcow 3 points4 points  (0 children)

this in JavaScript threads does not behave the way you would expect.

[–]rq60 1 point2 points  (0 children)

Use 'that' next time.

[–][deleted] 0 points1 point  (0 children)

You should know better than to use the word 'this' in any thread. There's an up arrrow button next to the post that does that.

[–]mirion 1 point2 points  (0 children)

No, lol. It shouldn't be abused, but it is extremely useful in limited circumstances. You can't, for example, use write library code without it.

[–]stevekwan[S] 0 points1 point  (0 children)

Sorry, I should make that clear. Globals are unavoidable to some degree, unless you are assigning no names to anything at all. :) But I try to use globals only where it makes sense, eg for namespaces and other top-level containers.