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>
console.log($("div").__proto__)and I see an object with a prototype jQuery object, no pureHTMLCollectionobjects. If not, and I did not understand something, can you collect a snippet here? - Alex Krassinit.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