What is the difference between these two methods of writing $ instead of jQuery in WordPress [closed]
IT Nursery
May 21, 2022
0
What is the difference between these two methods of writing $ instead of jQuery in WordPress
(function($) {
// $ Works! You can test it with next line if you like
// console.log($);
})( jQuery );
… Which I found here
and
jQuery(function ($) {
/* You can safely use $ in this code block to reference jQuery */
});
… Which I found here
1 Answer 1
The first is a pattern called a closure. It’s not unique to jQuery. You could just as easily write
(function(someVar) {
// Inside the closure, someVar == "test"
})("test");
Basically, you’re manually passing jQuery into the closure by referencing the jQuery object externally and aliasing it to $ inside the context of the closure.
The second pattern is unique to jQuery. It’s one of the library’s shortcuts to the DOM ready event. The following calls are all equivalent:
jQuery(document).ready(function($) {
// Use $ inside here like normal
});
jQuery.ready(function($) {
// Use $ inside here like normal
});
jQuery(function($) {
// Use $ inside here like normal
});
In all three examples, you’re also passing the jQuery object into your function as the variable $ so that it’s available within the local scope.