What is known as the factory function in jquery is "$()". It is essentially a DOM object, but the methods it uses are all encapsulated in jQuery, so we cannot pass "$() ” to use JavaScript methods, similarly DOM objects cannot use jQuery methods.
Related recommendations: "jQuery Tutorial"
The factory function in jquery is known as "$() ". In jQuery, no matter which type of selector we use, we need to start with a "$" sign and a pair of "()".
"$" is an alias for jQuery "class". $() constructs a jQuery object; therefore, "$()" can be called jQuery's constructor.
Factory function "$()" is essentially a DOM object, but the methods it uses are encapsulated in jQuery, so we cannot use JavaScript methods through "$()", the same DOM Objects also cannot use methods on jQuery.
We start with $ and introduce the entire jQuery architecture
Take the 1.11.3 version of jQuery as an example. The place where $ appears as a function name is at the end of the source code:
window.jQuery = window.$ = jQuery;
The jQuery is a function defined earlier, which appears in line 70 of the source code.
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }
This function is equivalent to a factory function. It returns an object internally, so that it can be created without using new. jQuery object
So there is no difference between new $().xxx and $().xxx. This is also in line with jQuery’s design concept of “write less, do more”
In line 2882 of the source code :
// Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn;
The prototype object of init is replaced with jQuery.fn, which is actually replaced with the jQuery function’s own prototype object jQuery.prototype
In line 89 of the source code:
jQuery.fn = jQuery.prototype
Like this We can easily write jQuery extension methods
For example:
jQuery.fn.alertMsg = function(msg){ alert('msg'); }
Use:
$().alertMsg('Hello World!');
The overall structure of jQuery is almost here
The following It is a simplified version of jQuery architecture, easy to understand
(function () { function jQuery(selector) { return new jQuery.prototype.init(selector); } // jQuery对象的构造函数 jQuery.prototype.init = function (selector) { } // jQuery原型上的css方法 jQuery.prototype.css = function (config) { } // 将jQuery原型上的方法都放到init的原型链上 jQuery.prototype.init.prototype = jQuery.prototype; window.$ = window.jQuery = jQuery; })();
Relationship diagram:
For more programming-related knowledge, please visit:Programming learning website! !
The above is the detailed content of What is known as the factory function in jquery?. For more information, please follow other related articles on the PHP Chinese website!