Recently, I stumbled upon this tweet:
Is there still a real reason to do (function ($) { … }(jQuery)) ?
— Dustin Diaz (@ded) January 17, 2014
The jQuery wrapper format is slightly different than the one I’ve been using for the past few years. I then queried the Internet:
What’s the difference between ( function( $ ) { … } ) ( jQuery ) ; and ( function( $ ) { … } ( jQuery ) ) ; ?
— cfree (@craigfreeman) January 17, 2014
Here it is written a little more clearly:
(function($) { ... })(jQuery);
vs.
(function($) { ... }(jQuery));
Justin was kind enough to break this down for me:
“So, you’ve got this anonymous function, right? Ok, now call it.” versus “So, you’ve got this anonymous function and you’ve called it, right?”
The results are the same, but the execution is slightly different. As I get deeper into the JavaScript world, I’m catching these differences – my eye is being trained to find these subtleties – which is both scary and awesome.
To answer Dustin’s question, yes – we do still need to use this kind of wrapper for jQuery. WordPress, specifically, still enqueues jQuery in no-conflict mode, meaning we can’t utilize the $
shortcut in our scripts without using this kind of wrapper. The wrapper serves as a namespace for our scripts, separating our code from any other scripts using the $
object for their own purposes.
Rick Shaffer liked this on Facebook.
Richard Molinari liked this on Facebook.
Jared Wolff liked this on Facebook.