Home >Web Front-end >JS Tutorial >A brief analysis of jQuery's initialization and object construction_jquery

A brief analysis of jQuery's initialization and object construction_jquery

WBOY
WBOYOriginal
2016-05-16 18:08:05739browse

To summarize:

1. The entire class library is defined in an anonymous function, eliminating the generation of global variables;
2. Passing undefined as a missing parameter prevents the pollution of undefined variables;
3. It can be seen that $(...) actually returns an instance of the jQuery.fn.init object, and then points the prototype of the object to jQuery.prototype (statement jQuery.fn.init.prototype = jQuery.fn ), so the generated instances share the methods and properties in jQuery.prototype and implement chain programming operations;
4. Finally, export jQuery and $ as global variables through window.jQuery = window.$ = jQuery.

Copy code 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 'enhanced '
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);
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