My previous work and study mainly focused on native js, and I have never been very familiar with jQuery. But jQuery, as one of the best js class libraries today, must take a good time to learn, today, it was just a pain point. I read some code in it and summarized it:
1. The entire class library is defined in an anonymous function to prevent the generation of global variables;
2. Pass undefined as a missing parameter to prevent contamination of the undefined variable;
3. we can see that $ (...) actually, jQuery is returned. fn. the instance of the init object, and then point the prototype of the object to jQuery. prototype (statement jQuery. fn. init. prototype = jQuery. therefore, the generated instances share jQuery. methods and attributes in prototype and implement chained programming;
4. Finally, use window. jQuery = window. $ = jQuery to export jQuery and $ as global variables.
The Code is as follows:
(Function (window, undefined ){
// Define a local copy of jQuery
Var jQuery = (function (){
Var jQuery = function (selector, context ){
// The jQuery object is actually just the init constructor 'enabled'
Return new jQuery. fn. init (selector, context/*, rootjQuery */);
};
//...
JQuery. fn = jQuery. prototype = {
Constructor: jQuery,
Init: function (selector, context, rootjQuery ){
//...
}
//...
};
// Give the init function the jQuery prototype for later instantiation
JQuery. fn. init. prototype = jQuery. fn;
//...
// Expose jQuery to the global object
Return jQuery;
})();
//...
Window. jQuery = window. $ = jQuery;
}) (Window );