Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these two parameters in the jQuery source for?

The jQuery source is wrapped in a closure, like this:

(function(window, undefined) {
   //awesome jQuery library code in here
})(window);

I don't understand why either of these parameters are needed.

Since window is a global variable, why does it need to be passed in? What's the purpose of passing in a global parameter and accessing it inside the closure with the same name?

What's the undefined parameter for? Why isn't any value passed to it?

like image 220
Peter Olson Avatar asked Oct 27 '11 22:10

Peter Olson


People also ask

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.

What is a parameter jQuery?

jQuery param() Method The param() method creates a serialized representation of an array or an object. The serialized values can be used in the URL query string when making an AJAX request.

Which is the parameters used for jQuery AJAX method?

By default ajax() method performs http GET request if option parameter does not include method option. The second parameter is options parameter in JSON format where we have specified callback function that will be executed when request succeeds.

What are the parameters of AJAX?

The parameters specifies one or more name/value pairs for the AJAX request. The data type expected of the server response. A function to run if the request fails. A Boolean value specifying whether a request is only successful if the response has changed since the last request.


1 Answers

I'm pretty sure this has been answered already, but:

  • passing in window a) allows code compression to munge the name (i.e. replacing it with a single-letter variable name within the anonymous function) and b) ensures that the variable references the window object at the time the library is defined, just in case anyone redefines window in the global scope after jQuery is loaded.

  • including undefined as an argument (but not passing in a value) does the same thing for undefined, allowing variable munging and avoiding problems if the undefined variable is redefined (yup, Javascript allows this).

I believe in both cases this is supposed to speed up references to the variable, as it makes both global variables available in the function scope, which the interpreter will search before looking in the global scope. But I can't honestly imagine that the performance difference here is substantial - I think the biggest issue is the variable name munging, which makes for more compact code when minified.

like image 73
nrabinowitz Avatar answered Nov 10 '22 00:11

nrabinowitz