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:
What do you think?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With