4

I am trying to understand how to "chain" JavaScript events together like jQuery does. I found a question here on S.O. that was similar to my goal, but I do not understand the code in the answer.

Code Source

(function( window, undefined ) { 
...etc...
}(window)

What does that mean? What is it doing? It reminds me of Jquery's $(document).ready(){} function, but I don't know why this person wrapped his code in this anonymous function that passes window and undefined.

My ultimate goal is to figure out how to execute methods on an object by chaining methods together like jQuery. I know that jQuery already does this but I am looking into this primarily for growth as a developer.

Community
  • 1
  • 1
quakkels
  • 11,676
  • 24
  • 92
  • 149

2 Answers2

3

It defines a function (using a function operator as opposed to a function statement). The parenthesis around it ensure that it is treated as the operator rather than the statement.

It then executes it immediately, passing window as an argument.

Essentially, this is the same as:

var myFunction = function( window, undefined ) { 
...etc...
};
myFunction(window);

… but without the interstitial variable.

This has nothing to do with jQuery style function chaining, where each method effectively ends with return this (so calling a method on the return value of another method is the same as calling it on the original object).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for making the distinction between function operator and function statment. Also, thanks for pointing out that jQuery chaining is accomplished by `return this` rather than the above syntax. – quakkels Nov 08 '10 at 19:42
3

When a function is called with fewer arguments than its signature contains, the trailing arguments are assigned the value undefined.

So the above is a roundabout way of getting hold of the undefined value even if some lunatic has redefined it by saying var undefined= 'hello';. (This is illegal anyway in ECMAScript Fifth Edition's ‘strict mode’, but JavaScript coders do some weird things sometimes.)

There isn't really a good reason for passing in window like this though... the traditional way to get window if you can't rely on window is to call a function directly and use this.

Either way, this is simply defensive coding against pathological author JavaScript. It's not something you should worry about whilst writing your own code (in any case there's no way you can stop every way someone might mess up their JS environment), and it's nothing to do with chaining.

bobince
  • 528,062
  • 107
  • 651
  • 834