1

What is the use of functions which self execute?

(function(w,d) {...})(window, document);

And why do they pass window/document which are global variables?

bhb
  • 2,476
  • 3
  • 17
  • 32

6 Answers6

2

The reasons are:

  • We need to create private scope, everything declared inside that function is not polluting the global namespace.
  • Keeping code readable with shorter names. This is for your question: why do they pass window/document which are global functions?

Update: add 1 more reason

  • Create closure to capture variable inside a loop.

For example:

for (var i=0 ; i< count; i++ ){
  (function(index){
   //do something with current index
  })(i);
}

This is usually the case when you need to do something later on after the loop has finished and still need to have reference to the index. Like attaching click event handlers for a list of objects or using setTimeout

Bonus:

Due to self-executing function's ability to create private scope. There comes Javascript module design pattern. The idea of the pattern is to create a private scope for your private variables and methods (truly private), only public things that are needed to avoid polluting global scope

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • ES6 update: If you're only supporting recent browsers/mobile webviews or are working on a Node.js app, the need for this pattern is eliminated by the use of `let` var statements because they are scoped to blocks rather than functions. Also, fat arrow functions do not auto-map to window or other global objects. – Erik Reppen Jun 10 '16 at 16:05
1

What is the use of functions which self execute?

This is an anonymous function, which is immediately called. The purpose of this is that if the function doesn't need to be called from anywhere else, you don't clutter up the namespace with making up random names. Such functions are often used as callbacks or event handlers.

And why do they pass window/document which are global functions?

In a page with FRAME or IFRAME tags, or pop-up/open-in-new-window pages, there may be more than one window and document.

Ben
  • 34,935
  • 6
  • 74
  • 113
1

Why do they pass window/document which are global functions?

So that inside that function scope window and document will be available as w and d.

One of the common practice of this is included with jQuery plugin development as:

(function($) {
   //...
})(jQuery); 

Since $ can be used in prototype too, this can create anamolities when mixing two libraries, but inside above function, $ will only represent jQuery but not prototype.

Starx
  • 77,474
  • 47
  • 185
  • 261
  • The changes you make to w and d does reflect/change outside. These local variables are mere references to the global window and document. Hence, changes made inside the function scope will make global changes! – Selvam Palanimalai Sep 10 '13 at 07:23
  • @SelvamPalanimalai, So do you mean if I do `$ = null;` then `jQuery` will also be null? – Starx Sep 10 '13 at 07:29
  • @SelvamPalanimalai, Here is a [fiddle](http://jsfiddle.net/CfFMY/) to prove your statement incorrect. – Starx Sep 10 '13 at 07:33
  • @SelvamPalanimalai, Interesting. Why didn't `jQuery`'s event handler stop working in my fiddle. – Starx Sep 10 '13 at 07:38
  • @Stark: I am trying to figure that out :P. Will let you know if I figure out something. – Selvam Palanimalai Sep 10 '13 at 07:40
  • 1
    `$` is an object. By passing it, you pass a copy of the reference to the object. So manipulating the object inside the function will changed it outside the function (`w.name`). Overwriting `$` inside the function (`$ = null;`) will only clear out the reference to that object and not manipulate the object itself. – Yoshi Sep 10 '13 at 07:56
  • @Yoshi, So `window` is not an object? – Starx Sep 10 '13 at 07:57
  • Of course it is. Using `$` for the explanation was just an example. What I wrote is correct for all objects. – Yoshi Sep 10 '13 at 07:58
  • @Yoshi, So how did modifying `w.name` inside function affect `window` in Selvam's fiddle. – Starx Sep 10 '13 at 08:00
  • Please read what I wrote: *So manipulating the object inside the function will changed it outside the function (`w.name`)*. That is to say, `w === window`. – Yoshi Sep 10 '13 at 08:01
  • @Yoshi, Please be patient with me. I am confused as you said _will only clear out the reference to that object and not manipulate the object itself_. How is `$ = null;` and `w.name = "john";` diffrent? Is destroying object with `null` different that manipulating? – Starx Sep 10 '13 at 08:06
  • ;) The first one (`$ = null;`) removes the reference to `jQuery` which was stored in `$` by overwriting that reference with `null`. So `$` no longer points to the same object. Where as in `w.name`, `w` still points to `window` because both variables have a copy of a reference to the same underlying object. – Yoshi Sep 10 '13 at 08:07
  • @Yoshi, Nice I understood now. Thanks :) – Starx Sep 10 '13 at 08:11
1

The idea is you pass copies of the global variables so anything you change within the scope of your self-executing function does not affect the external reference. It also allows you to declare global variables within that function which won't clash with existing variables.

In a nutshell, the goal here is to restrict scope.

James
  • 80,725
  • 18
  • 167
  • 237
  • But why pass the function parameter at all. Can't we do `(function() {var w = window, d = document})()`. Is this not same as passing the params – bhb Sep 10 '13 at 10:48
  • There is no difference, however, by passing the global variables in as parameters (better known as global imports) we can change the definition, a good example of where this is useful is jQuery & various other languages make use of the $ variable so on import you could rename one of the scripts for more clarity - another reason is readability, it makes it easy to see your codes dependencies. Although, that's all been wrapped up in a nice little utility library called RequireJS :) – James Sep 10 '13 at 11:13
1

Self executing functions also called as Immediately-Invoked Function Expression(IIFE) have multitude of uses. The most common ones are:

Prevent pollution (using closure)

Its a better practice to envelope all your code into a function scope to avoid littering the global namespace. "Variables and functions defined within a function may only be accessed inside, but not outside, that context, invoking a function provides a very easy way to create privacy."link

Class-based inheritance design: 

JavaScript has prototypal inheritance. But lot of class-based custom implementations are out there which use self-executing functions [1]

Global and window objects are passed for easier references. Changes to the properties of these objects DO reflect outside too.. The changes you make to w and d does reflect/change outside. These local variables are mere references to the global window and document. Hence, changes made inside the function scope will make global changes! [fiddle]

Selvam Palanimalai
  • 1,550
  • 1
  • 10
  • 13
0

These are anonymous functions being used as closures returning a function or a collection to functions with access to a set of common captured variables declared in their common parent function closure, not polluting the global namespace and being passed around.

Very basic exemple:

 keepsTrackOfTimesUsedWithoutPollutingNamespace = function()
 {
     var right = 0; 
     var left = 0;
     display = function(){console.log("right got executed " +right+" times and left got executed " + left +" times.\n";}
     return [
          function()
          {
               right += 1; 
               display();
          },
          function()
          {
               left += 1;
               display();
          }
          ]
 }
Jules G.M.
  • 3,624
  • 1
  • 21
  • 35