I saw this code (explicly it’s in jQuery, with modification)
(function(window,undefined){
var jQuery=(function(){
var jQuery=something;
jQuery.xxx=xxx;
//...
return jQuery;
})();
//...
window.jQuery=window.$=jQuery;
})(window);
While I understand wrapping code in a inline function call can clearly define the variable scope, I don’t understand the benefits of
- passing
windowwith a parameter instead of using it directly, - getting an instance of
undefinedby a undefined parameter, and also - defining
jQueryby the return value of another inline function call.
Can somebody explain a bit?
EDIT write #3 more clearly:
What I understand is that the code defines jQuery inside another function then return it.
//(function(window,undefined){
var jQuery=(function(){
// Inside this function defines jQuery and return it?
var jQuery=function(selector,context){
return new jQuery(selector,context); //simplified
};
jQuery.xxx=xxx;
//...
return jQuery;
})(); // This executes the inline function and assign `jQuery` with the return value???
//... })(window);
This is more like the following:
function define_jQuery(){
// Inside this function defines jQuery and return it?
var jQuery=function(selector,context){
return new jQuery(selector,context); //simplified
};
jQuery.xxx=xxx;
//...
return jQuery;
}
//(function(window,undefined){
var jQuery=define_jQuery(); // This executes the inline function and assign `jQuery` with the return value???
//... })(window);
Wouldn’t it be more simpler to do:
//(function(window,undefined){
var jQuery=function(selector,context){
return new jQuery(selector,context); //simplified
};
jQuery.xxx=xxx;
//...
//... })(window);
Answering these questions each separately:
Why
windowpassed in? Because dereferencing a variable in JavaScript is painful. Passing in an instance means you don’t have to. Typically the mechanism looks like this:In this scenario, one need not go to the global scope to dereference any of these three (and jQuery can be in
.noConflict()to boot).This is valid JavaScript:
undefined = 2;. I grant that is very foolish, but it is possible. But if one accepts one more argument in a function than is passed, one is confident it is truelyundefinedand not a hacked copy of it.Returning jQuery from a previous function allows method chaining:
$('#sel').func1().func2(). This is possible because func1 probably looks something like this:return $(this).bla_de_bla()is short-hand for:It also presumes that .bla_de_bla() also returns
$(this)EDIT: modified #3 to note that it’s best at chaining rather than circumnavigating around
.noConflict()and mis-named$.