Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Window object always accessible?

We see this approach used all the time:

(function (window) {
    var document = window.document,
        location = window.location,
        navigator = window.navigator;
})(window)

When studying above snippet I wonder why a globally accessible object like window is passed as an argument to a function. Could it be that:

  1. The developer can not with 100% certainty know that window is accessible from within the local function scope?
  2. Is is good practice because you make your intentions clear to other developers that read your code.
  3. You've seen John Resig do it so it must be finger lickin' good!

What do you think?

like image 480
ChrisRich Avatar asked Aug 15 '12 00:08

ChrisRich


People also ask

What is JavaScript window object?

The Window ObjectIt represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object.

Is global the same as window?

The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment. In a browser it is named window , for Node. js it is global , for other environments it may have another name.

What is the difference between window and document object?

The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc.


1 Answers

It makes the code more portable.

You can copy and paste the code to an environment that does not have global window object defined (e.g. node), but is API compatible for all the things you care about within your code. Then you only have to modify the argument passed to the function.

A slight modification that makes the code clearer:

(function(root){
    var document = root.document,
        location = root.location,
        navigator = root.navigator;
})(window)
like image 123
Matt York Avatar answered Oct 05 '22 21:10

Matt York