5

As a style convention I like to be explicit when I'm accessing variables in the global scope, preferring

window.example = "Hello";
window.alert(window.example);

to the less verbose

example = "Hello";
alert(example);

I now have a module which could be used directly from the browser, or, if they're available, from a web worker. In web workers the global object is called self, while in the browser it's called window.

The window object has a self property, so self.example = "Hello" would work in both contexts, so long as no-one redeclares self (as they often do: var self = this).

What's the best convention to go with?

  • Use self and hope no-one declares a conflicting self.
  • If window is defined, use window, otherwise use self.
  • Something else?

Having thought about it, I'm inclined to go with the second one.

Community
  • 1
  • 1
RichardTowers
  • 4,682
  • 1
  • 26
  • 43

3 Answers3

7

In the global scope, either in the page or a web worker, you can write code like this:

(function( global ) {
  // ... whatever
}( this );

Then inside that main outer function you can use "global" (or call it "window" or "self" or "whatever") and it'll work in either context (or in Node.js for that matter).

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

I'd suggest

var global; try { global = window } catch(e) { global = self }
matt3141
  • 4,303
  • 1
  • 19
  • 24
  • Surprisingly, this seems to throw a Reference Error when used in the web worker. Chrome says: "ReferenceError: Can't find variable: window". I should mention that I'm using requireJS to load this module from my worker, so I guess that might be the source of some weirdness. – RichardTowers Jun 22 '12 at 19:07
  • apologies, I forgot the harsh handling of a variable that doesn't exist. fixed it. – matt3141 Jun 22 '12 at 19:19
  • `global = typeof window !== "undefined" && window !== null ? window : self;` also seems to work without error. I do like @Pointy's answer though. – RichardTowers Jun 22 '12 at 19:32
0

You could create your own reference to either window or self:

var my_window = window || self;
jackwanders
  • 15,612
  • 3
  • 40
  • 40