简体   繁体   中英

Understanding jquery source code

I have recently started to delve deeper in to JavaScript and have come across this code construct in JQuery.

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

Reading on stack overflow (and elsewhere) I have come to the conclusion that this is the same as

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

foo(window);

Am I correct in my assumption? If so, what are the advantages of the former? (other than confusing newbs)

There are several things you need to know to make sense of it:

  1. It is an anonymous function, which simply means it does not have a name.
  2. The function is called immediately after it is declared. You see the open parenthesis on line 2, immediately after the function definition? That means, "call this function".
  3. Only one parameter is passed to the function. That parameter is "window", which is the name of the global scope inside of a browser.
  4. The function being called actually expects *2* parameters, but we're calling it with one. Javascript lets you call functions with more or fewer parameters than the function actually expects. There are ways of getting to the list of parameters that was passed.
  5. Since we are only passing one parameter, the second parameter will automatically be set to "undefined". "undefined" is a special javascript value that means, get ready, "undefined".
  6. It just so happens that we have also named our second parameter with the name "undefined". So in effect, we have created a local variable (parameters are very much like local variables) that is named undefined, and whose value is undefined.
  7. Why on Earth did we do that? It is a way of ensuring that, within our anonymous function, if we refer to "undefined", it really will have the value of "undefined". If we didn't do that, and some crazy code outside of our scope redefined "undefined" (by saying something like "undefined = 42"), then we'd write code thinking we were referring to undefined but we'd actually be referring to 42. These shenanigans with passing 1 parameter but expecting 2, and calling the second one undefined, protects us from such nonsense.

I hope that's clear, let me know if it is not. I learned all that from Paul Irish's video mentioned above.

This is an anonymous function. It is created and then goes out of scope, which here is the advantage. It is created and instantiated immediately. What is good about this is that it is not going to collide with any function on the global namespace, and thus will not obliterate anything you may have included on the page.

It is an anonymous function, it has quite a few benefits, like being only active in the current scope. You can read more about it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM