Create the jQuery plug-in. The basic format is the above Code:
Copy codeThe Code is as follows:
(Function ($)
{
// Add code here
}) (JQuery)
How do we understand it?
Step 1: function ($) {} defines an anonymous function with a parameter $, which is the parameter name. It is no different from other parameter names.
Step 2: (function ($) {}) (jQuery)
When we want to execute an anonymous function, we usually use var func = function ($) {}, and then func (parameter. Here, func is a Function object. But more concise (function ($) {}), then brackets are used, and the content of the brackets is also returned, which is also a function object. Run the following command: (function ($) {}) (jQuery)
Step 3: In this case, we actually execute the anonymous function defined above and provide a parameter value for this anonymous function during execution: jQuery.
Step 4: The above expression is equivalent:
Var func = function ($ ){};
Func (jQuery );
That is, the anonymous function is defined and executed once with jQuery as the parameter.
What is the role here?
1. Solve the $ symbol conflict problem
In jQuery, $ is used instead of jQuery to simplify the writing. But the $ symbol sometimes conflicts.
In the code of the above anonymous function, we can habitually use $ for writing, but we will use jQuery for execution, which avoids variable conflicts.
2. Solve the closure problem:
Generally, the function is written directly in the script. After execution, the undestroyed variables continue to exist and can be accessed normally. This is inconsistent with the private variable of the function we have always understood.
However, if we use this method to package all the required functions in this anonymous function, the local variables in the function will not be accessible from the external departments, in disguise, it serves to create private local variables. Only the members starting with this are accessible outside the plug-in.