Why to wrap JS “window” into a self-calling function before calling? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why to wrap JS “window” into a self-calling function before calling? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’ve been working in a codebase recently where there’s a number of javascript files, partially angularJS, jQuery, and other libraries. It’s been around for a bit, and I’m curious why a particular approach was used for so many of these extension methods or controllers in AngularJS.

So, every time a new AngularJS object is created, it’s wrapped in a self-calling function:

(function (w) {
  w.app.controller('ctrlName', function ($scope, $ngJSdependency, myOwnDependency) { 
   w.GlobalFunctions.exampleCallGlobalFunction();
   $scope someData = w.GlobalData.someData;
  }); 
})(window);

And for the life of me, I have no idea why. I’ve noticed no function difference between removing the self-calling function and replacing every reference to w with window. Is there a downside to making those changes and replacing everything with window? It feels much cleaner, and works better with my IDE tools as well.

Thanks!

Answer

There are (at least) four advantages to that strategy in older code that doesn’t use modern modules, three really minor ones and one fairly useful one (but only related to the function, not the window part):

  1. w is slightly shorter than window. 😀

  2. By making w a local within that function call, it’s found in the local environment when it’s referenced, rather than the JavaScript engine having to look for window in the local environment, not find it, and go out to the outside environment to find it.

  3. The window global on at least some browsers (I have to check the spec to see if it’s specified) is an accessor property, which means that in theory, every reference to it is a function call. So const w = window; calls that function once and remembers its return value, whereas using window everywhere (in theory) calls the function repeatedly. But function calls are really fast in JavaScript.

  4. (Not directly related to passing window into the function.) The function provides a private scope for putting other things that don’t need to be accessed outside the function.

#4 is probably the most useful, and as I mention above it’s not really related to the window aspect, you could do the same thing without the window/w thing.

In modern environments you’d get #3 by using modules, and if you wanted #1 and #2 you’d do const w = window; or similar.

We are here to answer your question about Why to wrap JS “window” into a self-calling function before calling? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji