Possible Duplicates:
How does this JavaScript/JQuery Syntax work: (function( window, undefined ) { })(window)?
What advantages does using (function(window, document, undefined) { … })(window, document) confer?
i have seen many javascript libraries create a variable named "undefined", iam unable to figure out its purpose, below are lines copied from jQuery library
* Date: Wed Feb 23 13:55:29 2011 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
Please suggest me the reason and benefits of doing so!!
What you will see is something like this:
(function(undefined) {
/* lots of code */
}());
This creates an anonymous function and immediately executes it. The function has a parameter called undefined
. Since there is no argument passed to the function, the variable undefined
is in fact the Javascript primitive value undefined
.
So why do you want to do this? Well, the problem is that you can actually create a variable with the name undefined
and set it to anything you like, e.g.:
var undefined = 'some text';
A test myvalue === undefined
within your code would then have unexpected results.
The anonymous function with the parameter called undefined
essentially "resets" the value of undefined
to the primitive value, so that you can check against it if you wish without having to worry about whether it has the right value.
Its to make sure undefined
is actually undefined
. Paul Irish calls it the asshole effect, other js included on the page could change the meaning of undefined, and then you will get unexpected results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With