When you write a function like:
(function (foo, bar) {
return foo.getElementById(bar);
})(document, "myElement")
then the function is immediately called with arguments document
and "myElement"
for parameters foo
and bar
. Therefore, inside the function, foo.getElementById(bar)
is equivalent to document.getElementById("myElement")
.
Similarly, in your plugin example, you are immediately calling the function with the arguments jQuery, document, window
.
What indeed is meant by
function($)
?
The $
simply represents a reference to a jQuery
object that is passed in to the wrapper function. Later, when the anonymous function is called with (jQuery, window, document)
, the $
reference inside the function references the jQuery
object. This is done for a number of reasons, not least of which is that $
is quicker to type. It also allows the user to apply your plugin in wrapper to a particular instance of jQuery
, produced perhaps by jQuery.noConflict()
.
Why should I include
window
,document
andundefined
as arguments offunction($)
?
You don't need to include these. The original author's reasoning is that assigning function-local variables to reference these will shorten the time it takes to resolve these variables. I assert that the savings are negligible; I personally wouldn't bother unless I used a lot of references to window
and/or document
.
As for undefined
, the original author's purpose in including this is to ensure that someone hasn't altered the undefined
global variable in EcmaScript 4 (edit: actually ECMAScript 3 -- version 4 never made it) or earlier. Again, I can't envision this problem cropping up. If you're truly worried that this could be a problem, just include something like this in your function:
if(typeof undefined !== "undefined") {
undefined = void 0;
}
If I do it, how do I access the actual
window
anddocument
objects?
All you have to do is make sure that the function call at the end of your anonymous function passes in the actual (jQuery, window, document) parameters. Or, don't include the window
and document
arguments in your function signature. Either way, you will be referring to the actual objects, regardless of the level of indirection.
undefined
what, and why?
undefined
is a global variable of type "undefined". Fields that have not been initialized are exactly equal (===) to undefined. It allows the programmer to differentiate between a deliberately null value and a simple uninitialized one. In ECMAScript 5 and later, undefined
is read only. Prior to that, it is possible that other code could modify the value of undefined
. You can always get the true value undefined
with the expression void 0
... as in myUndefinedVar = void 0;
.