Reputation: 1960
Do anyone can explain and prove which one of examples is "more correct"?
A: pass object as an argument
(function($){
$.doStuff();
})(jQuery);
B: retrieve object within the function
(function(){
var $ = jQuery;
$.doStuff();
})();
I really like B because of its readability. Only technical difference between A and B is that B has to lookup one more scope. I consider this as marginal difference so why is "recomended" the A way?
Note that the jQuery is just example. Important is the nature of the problem: Pass as argument or retrieve within the function?
Upvotes: 3
Views: 535
Reputation: 18224
Both are equivalent, but I like the first example (passing as an argument) more as it saves you one line of code. That also means that your function does not contain unnecessary logic.
Upvotes: 1
Reputation: 414086
The second way will only work if the name of the jQuery library is really "jQuery". It's possible (though unusual) to call .noConflict()
like this:
window.banana = jQuery.noConflict( true );
Then, your first example would still work:
(function($) {
$.doStuff();
})( banana );
but your second example would fail (as written). Of course, you could similarly hard-code the name "banana" into the second one too, but if that function isn't directly under your control, you can't; plus it's a "DRY" violation.
Imagine that you've got an initialization function being loaded in a separate JavaScript source file; perhaps it's a 3rd-party script. If you want to call that function at initialization time, you'll have more flexibility if the function takes the jQuery reference as a parameter instead of just making the assumption that the global symbol is anything in particular.
alienInitializationFunction( banana );
will still work, in other words.
Upvotes: 1