Why does jQuery use the prototype property for plugins?

One assigns a plugin for the jQuery prototype property. What is the point of doing this if you are not using "new" with jQuery? Is there only one jQuery instance there? Thus, is it possible to connect plugins directly to a singleton jQuery object?

+4
source share
1 answer

Plugin methods should be automatically added to every new jQuery object that is created.

jQuery.fn same as jQuery.prototype , so the purpose of the jQuery.fn plugin jQuery.fn is to add it to the jQuery prototype, so whenever a new jQuery object is created, this method will be automatically available. Technically, this is a jQuery.fn.init object, but the idea is the same.

A jQuery call with a line like this:

 $(".foo") 

creates a new jQuery.fn.init object, which gets its prototype from jQuery.fn (where the plug-in methods are defined).

Here is the corresponding jQuery code that shows the creation of a new object:

 // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 
+3
source

Source: https://habr.com/ru/post/1435708/


All Articles