Using window object

I've seen lots of people using window. when calling some variable. But aren't all the variables of a same window actually in window? Example:

window.onorientationchange = function() {
  var orientation = window.orientation; // <-- WHY?
  switch(orientation) {
    /* ... */

But the same people use alert(), document, etc. So why?


At certain times you want to expose only certain functions/variables to be explicit properties of the window.

(function() {
   var jQuery = function(selector) { alert( selector ) }

jQuery // not defined

If we alter it to be:

(function() {
   var jQuery = function(selector) { alert( selector ) }
   window.jQuery = jQuery;

then we "expose" it from a private namespace explicitly.

And yes, you do not have to explicitly declare window. to invoke methods such as alert, but everyone has their own style of coding and everyone has their own degree of how explicit their statements should be.

Some people explicitly prefix window. to global methods such as alert in order to avoid any confusion. Let's say you defined a function in a private namespace that was named alert, for example...

(function() {
   function alert() {}
   alert('lol'); // does nothing
   window.alert('lol') // does something

We cannot use alert inside of that private namespace to do our alerting, since we defined a function with exactly the same name. We have to explicitly reference the window.alert method to get around that.

But for general purposes, I would say it's perfectly fine to not prefix things with window. unless you are exposing things in a private namespace to the global namespace. So please use document and alert and such as is, in your code.

In many javascript tutorials alert(), document() and so on are used without fully qualified window object and I think they just repeat that code.

Need Your Help

How to set a timer for an iOS app with Xcode?

iphone objective-c ios xcode nstimer

I've been trying to get a timer to show at the bottom left corner of my app by using an NSTimer, and making the "elapsed time" show as UILabel on the bottom left corner but it hasn't been working f...

Chrome CSS image transitions affect other elements

html css google-chrome css-transitions

I have a menu with images as backgrounds for buttons which animate on hover.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.