So I am trying to understand how jQuery works internally. jQuery exposes a global $ variable, which can be used like:
$('.abc') // returns a list of DOM nodes having class abc
$.ajax() // used to perform AJAX requests
As you can see, $ is a function, from statement 1, while it's an object, from statement 2. Now I know that this is possible because of function Objects in JavaScript, meaning that a function is also an Object in JavaScript, and hence you can attach methods to it. But I am not sure how this is achieved internally?
I was looking at this blog post which explains how the 'constructor pattern' can be used to mimic jQuery, but how would you attach methods on $ using that pattern? Or does jQuery use some completely different pattern? Here is a small implementation of jQuery from that. This code can do $(selector), but how do I add $.method in it?
// Mini jQuery implementation
var $ = (function() {
var JQuery = function(selector) {
if (selector === "document") {
this.elements = [document];
} else if (selector === "window") {
this.elements = [window];
} else {
this.elements = document.querySelectorAll(selector);
}
return this;
};
JQuery.prototype.each = function(callback) {
this.elements.forEach(function(element) {
callback(element);
});
return this;
};
JQuery.prototype.addClass = function() {
if (arguments.length === 0) return this;
else {
this.each(element => {
element.classList.add(...arguments);
});
return this;
}
};
return function(selector) {
return new JQuery(selector);
};
})();
// Use our mini jQuery to turn background of matching Nodes green
$(".abc").addClass("highlight");
.abc {
background : red;
}
.abc.highlight {
background: green;
}
<div class="abc">Node 1</div>
<div class="abc">Node 2</div>