I think I understand the module pattern, but why do some examples pass JQuery in as a parameter like this:
Namespace.AppName = (function ($) {
// Code Here
})(jQuery);
If I don't pass in JQuery I can still use the Jquery library just fine by making $() calls inside the module. So why do some people do this?
The Module Pattern is one of the most common design patterns used in JavaScript and for good reason. The module pattern is easy to use and creates encapsulation of our code. Modules are commonly used as singleton style objects where only one instance exists. The Module Pattern is great for services and testing/TDD.
For the full set, see JavaScript Design Patterns. JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code. For those that are familiar with object-oriented languages, modules are JavaScript “classes”.
This provides loose coupling to support well-structured code. For those that are familiar with object-oriented languages, modules are JavaScript “classes”. One of the many advantages of classes is encapsulation - protecting states and behaviors from being accessed from other classes.
However, when outside the module, contents are unable to be referenced. A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:
The idea here is that you pass jQuery
as $
to the inside function, making sure that the $
IS jQuery. This is commonly used to protect code that uses $
especially when using jQuery along with other libraries that use $
like mootools.
example, if you had this code in the <head>
<!--load jQuery-->
<script src="jquery.js"></script>
<script>
//"$" is jQuery
//"jQuery" is jQuery
</script>
<!--load another library-->
<script src="anotherlibrary.js"></script>
<script>
//"$" is the other library
//"jQuery" is jQuery
//out here, jQuery code that uses "$" breaks
(function($){
//"$" is jQuery
//"jQuery" is jQuery (from the outside scope)
//in here, jquery code that uses "$" is safe
}(jQuery));
</script>
In order to use the $ 'safely'. Most developers are more comfortable with the '$' instead of jQuery.
When using the $ as a global, it may conflict with other JS libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With