Let's break this template further and look at each of the parts separately:
1. Self Invoking Function:
Self-invoking functions are the functions which get invoked as soon as it gets defined. They create a scope for all the variables and functions defined within the function so they don't leak to global scope.
A function expression on the other-hand, can be anonymous, and you can invoke them right away by putting parenthesis at the end. Putting any operator, like +, -, ! etc., in front of the function will make the parser think that it's a function expression.
Lastly, you may have noticed that we actually pass 'jQuery' to the function and make '$' the parameter name. This way we can reference jQuery within function with '$'. Outside the scope of the function, you can continue to use '$' for other libraries. This avoids any conflict between jQuery and other libraries which share '$'.
2. Strict Mode
3. Constructor Function & Prototype
Modal is a constructor function which gets executed when 'new Modal()' is called. The important thing to note is that 'this' in modal function can change references based on how it is called.
If it's executed with the new operator like, 'new Modal()", then 'this' is bound to a newly created object and all the properties like 'options' are set on that object and everything works as expected.
However, if this function is called without the 'new' operator like 'Modal();' then 'this' is bound to the global object and it can clobber the global namespace. In this case, 'this.options' will be same as calling 'window.options'. Take a look at the example below which shows how the references of 'this' changes:
4. Main Plugin Function
This plugin function is the method which gets exposed to jQuery's prototype ($.fn). This is the method which gets called when you call '$('.my_modal').modal();'.
Interesting part about this method is how it puts the Modal object in the data params.
This enables the re-use of the same Modal object, if you show or hide the same modal multiple times on the page. Its an interesting technique to memorize object by using data attribute.
Another thing to note is that you can also pass string to call specific methods eg. $('.my_modal).modal('show'). This is done by using this line.
5. Constructor Property
Finally, the Constructor property which exposes the main Modal function object. This is useful for extending Modal or for changing the default settings e.g '$.fn.modal.Constructor.DEFAULTS.show = false;'. This will change the default settings for all the instances of the Modal.
There are some of the lessons I learned from this plugin pattern and it gives a great boiler plate for writing jQuery plugins. If you have learned some other things from this pattern, please share in the comments.