Code Analysis for creating plug-ins using jQuery

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.