Why am I missing a window object in a module template?

The following is an anonymous self-starting method.

It seems like good practice should go through the window as global. If the window is accessible everywhere, why is this done?

(function (global) { /* my code */ global["someName"] = someObject; })(window); 
+7
source share
2 answers

It skips the code needed to search for the area, since global is inside the function.


Change is a performance optimization. Scope in javascript is limited to a functional scope. global in this case is defined within this area, therefore, when the code falls on global[...] , it looks at its immediate volume (inside the function) and immediately finds global . Without this, he will have to move to the closing region, which in this case is the global javascript namespace and will look for the entire region for the window .

+6
source

The JavaScript browser translator must determine the scope of any variables found, starting from the local area itself and working its way out. Using function closure with window as the global parameter reduces the need to further expand the scope chain to find window .

window is available everywhere, but using global way it is in your example is more efficient.

+2
source

All Articles