How jQuery manages to implement the following:
If you make a request in the form of $('div') - it will return the HTMLCollection without any additional methods and properties of the library. At the same time, it retains the possibility called "call chain". For example, the call $('div').css('width',100) will be executed without problems. Initially, I thought methods were being "imposed" on an HTMLCollection . But looking, I realized that I was wrong.
Who knows the answer, please write the code snippet how it is implemented. Thanks for attention

Addition:

 var a = function(q){ q = document.querySelectorAll(q); console.log('1'); return this; } a.prototype.t = function(){ console.log('2'); return this; } function _(b){ return new a(b); } _('div').t() 
  • What does it mean " it will return the HTMLCollection without any additional methods and library properties "? I print console.log($("div").__proto__) and I see an object with a prototype jQuery object, no pure HTMLCollection objects. If not, and I did not understand something, can you collect a snippet here? - Alex Krass
  • In addition to the above and a reference to the source in the answer @Andrew B, I draw your attention to the following line: init.prototype = jQuery.fn; and a comment to it "// Give the init function the jQuery prototype for later instantiation" in 126,127 lines. Therefore, the functions are transferred in the prototype, no magic. - Alex Krass

1 answer 1

Normal if (проверить что передали) {} and method chain

About the method chain you can see a simple example here (you need to click a solution ). The meaning is that the method / function returns this , so You can call other functions / methods of the same object.

About magic with the definition of what was passed, you can look at the source code

Here is a piece of the source:

 // https://github.com/jquery/jquery/blob/2.2-stable/src/core.js // Define a local copy of jQuery 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 ); } // https://github.com/jquery/jquery/blob/2.2-stable/src/core/init.js jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } ... // Handle HTML strings if ( typeof selector === "string" ) { ... // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { ... // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { ... } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } ... }; 

As you can see, a simple iteration of options, which in some cases returns this .

Added by

If I understand correctly, you want to achieve a similar result:

 // Создадим функцию, которая возвращает нам новый объект "класса" worker (чтобы самим не писать new - по аналогии с jQ) var Styler = function(selector) { // Т.к. используем new, то у функции worker будет свой this return new Styler.worker(selector); }; // Добавим нашей функции Styler статическое поле worker, в котором будет храниться наш класс Styler.worker = function(selector) { // Назначим экземпляру объекта worker поле elements и сохраним в него список найденных элементов this.elements = document.querySelectorAll(selector); return this; } Styler.worker.prototype.css = function(name, value) { for (var i = 0; i < this.elements.length; i++) { // Т.к. в данный момент мы находимся в экземпляре объекта worker, то используем назначенное в конструкторе значение elements this.elements[i].style[name] = value; } return this; } Styler('div').css('color', 'blue'); Styler('div').css('font-size', '26px'); Styler('div').css('font-family', 'Arial').css('font-style', 'italic'); 
 <div>Подопытный DIV</div> <div>Подопытный DIV № 2</div> 

  • It does not work, something does not reach me. I did an example and failed to do what I wanted (Addition in question). - Node_pro
  • @Node_pro, did not fully understand the question. The answer is supplemented. Please see if you mean it. - Andrew B
  • Thanks for the answer, but almost the wrong way. If you call Styler('div') - I wanted it to return the HTMLCollection, while the Styler('div').сss() and the others that I specified also worked. - Node_pro
  • @Node_pro, I think, this is how it can be done only by HTMLCollection and NodeList . $('div') does not return a HTMLCollection , but a jquery object - Andrew B
  • I also think so, but try to display it in the console of the browser as I said and look =) - Node_pro