Should I use self or window to refer to the global scope?

As a style convention, I like to be explicit when I access variables in a global area, preferring

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

for less detailed

example = "Hello";
alert(example);

Now I have a module that can be used directly from a browser or, if available, from a web worker. In web workers, the global object is called self, and in the browser it is called window.

An object windowhas a self property, so it self.example = "Hello"will work in both contexts if no one overrides it self(as it often happens: var self = this ).

What is the best deal for you?

  • Use selfand hope that no one declares conflicting self.
  • window , window, self.
  • - ?

, .

+5
3

, , -, :

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

"" ( "" "" " " ), ( Node.js, ).

+6

var global; try { global = window } catch(e) { global = self }
+1

:

var my_window = window || self;
0

All Articles