What does it mean?:
(function($){
})(jQuery);
And what reason to use it? Thanks.
What does it mean?:
(function($){
})(jQuery);
And what reason to use it? Thanks.
You are creating a new scope in javascript by using a function (as {} does not create a new scope). Then you are immediately calling this function and capturing JQuery
from the outer scope and make it available inside as the variable $
It's a Self Executing Closure(self executing function).
Here you pass jQuery to this self executing function, that maps jQuery to dollar sign. Thus it can’t be overwritten by another library in the scope of its execution.
You will need to write such syntax, while writing a new plug-in, as you prefer to encapsulate your code inside seperate namespace
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
Revert the $ alias and then create and execute a function to provide the $ as a jQuery alias inside the function's scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
It is a self executing anonymous function. This function execute itself as it loaded.
It means :
// but execute itself
function ($) {
// to-do
}
Passing $
to function
prevents confliction from other libraries
like,
<!-- Using the $ inside an immediately-invoked function expression. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
(function( $ ) {
// Your jQuery code here, using the $
})( jQuery );
//Passing jQuery from here prevents $ variable which is also used by prototype
</script>