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 conflictingself
. - If
window
is defined, usewindow
, otherwise useself
. - Something else?
Having thought about it, I'm inclined to go with the second one.