Why are these two parameters in jQuery source?

The jQuery source is wrapped in closure, for example:

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

I do not understand why one of these parameters is needed.

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

What is the parameter undefined for? Why is no value passed?

+6
source share
1 answer

I am sure that this has already been answered, but:

  • passing in window a) allows code compression to change the name (i.e. replace it with the single-letter variable name in an anonymous function) and b) ensures that the variable refers to the window object while the library is defined just in case someone overrides window in the global area after loading jQuery.

  • including undefined as an argument (but not passing a value) does the same for undefined , allowing you to change variables and avoid problems if the undefined variable is overridden (yup, Javascript allows this).

I believe that in both cases this should speed up variable references, as this makes both global variables available in the scope of functions that the interpreter will search before searching in the global scope. But I canโ€™t honestly imagine that the performance difference is significant here - I think the biggest problem is renaming the variable name, which makes the code more compact when it is mined.

+11
source

Source: https://habr.com/ru/post/900247/


All Articles