At a website, I found the following code to make a jQuery plugin:
(function($){
// Our code here...
})(jQuery);
I don’t understand how the code above works. What I understand is that the code executes immediately because the very last () in function(){}(). So the entire code says that is an anonymous function that is run immediately.
But I don’t understand why the wrapping needs to pass jQuery and that inside it needs $ to be passed.
From my understanding, $ is an alias to jQuery, meaning practically the same. What is the meaning of $ and jQuery here? How does the overall code work as a jQuery plugin?
jQuery is the actual parameter. $ is the formal parameter. You could very well write:
One reason is convenience – it’s short. You might be using jQuery in noConflict mode with other libraries. Maybe typing
jQueryall the time is a hassle, or other plugins are following bad practices and using$instead ofjQuery. Either ways, you can use a self-calling function like the one above to solve the problem.