Home  >  Article  >  Web Front-end  >  Code analysis of jQuery creation plug-in_jquery

Code analysis of jQuery creation plug-in_jquery

WBOY
WBOYOriginal
2016-05-16 18:07:451071browse

To create a jQuery plug-in, the basic format is the above code:

Copy code The code is as follows:

(function ($)
{
//add code here
})(jQuery)


How do we understand?
Step one: function ($){} defines an anonymous function with one parameter. $ is the parameter name, which is no different from other parameter names.
Step 2: (function ($){})(jQuery)
When we want to execute an anonymous function, we usually use the form var func = function ($) { }, and then func (parameter) . Here func is a Function object. But the more concise (function ($) {}), when brackets are used, also returns the content of the brackets, which is also a function object. We can just execute it again: (function ($) {})(jQuery)
Step 3: At this time we are actually executing the anonymous function defined above, and providing a parameter value to the anonymous function during execution: jQuery.
Step 4: So in the end the above expression is equivalent to:
var func = function($) { };
func(jQuery);
That is, define an anonymous function and take jQuery as a parameter Execute once.

What is the function here?
1. Solve the problem of $ symbol conflict
In jQuery, we use $ instead of jQuery to simplify the writing. But the $ symbol sometimes conflicts.
In the code of the anonymous function above, we can habitually use $ to write it, but jQuery will be used instead when executing, which avoids variable conflicts.
2. Solve the closure problem:
Generally, for functions written directly in scripts, the variables that are not destroyed will continue to exist after execution and can be accessed normally. This is inconsistent with the function private variables we have always understood.
But if we use this method to wrap all the functions we need in this anonymous function, the local variables in it will not be accessible from the outside, which in disguise plays the role of creating private local variables. Only those members starting with this. are accessible outside the plug-in.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn