JQuery constructor constructor maps its functionality to another constructor
The fact is that jQuery is not really a constructor function and should not be considered as one. By definition, the responsibility of the constructor is to initialize the properties of the instance, which is actually not related to jQuery . In addition, a call to new jQuery() will be insensitive. jQuery is a factory function for instantiating jQuery.fn.init , no more .
Now, you might be wondering why they just didn't use jQuery as a real constructor?
Good, because they did not want the constructor that we call with new all the time, they needed a factory function. This is fine with me, however, when I tend to disagree, it is that their pattern is very mysterious and does not quite reflect the intention .
It would be much better, in my opinion, to choose the best names:
function jQuery(selector, context) { return new jQuery.Set(selector, context); } jQuery.Set = function (selector, context) {
I almost jQuery.fn.init to jQuery.Set , and all of a sudden this all makes more sense to me. When looking at the code above itโs easy to see that:
jQuery is a factory function for creating jQuery.Set objects.jQuery.fn exists only as syntactic sugar, instead of writing jQuery.Set.prototype all the time to change the prototype.
Now in the source we also see that they are doing the following, which is unreasonable, since jQuery not a real constructor, but jQuery.prototype.init and since we are not creating jQuery instances, setting jQuery.prototype seems useless:
jQuery.fn = jQuery.prototype = { constructor: jQuery
One reason for this is, of course, that they want to host people who can modify jQuery.prototype instead of jQuery.fn .
However, another important reason is that they may have wanted somejQueryObj instanceof jQuery return true, while this is usually not the case. If you take the template above (with jQuery.Set), you will notice that:
jQuery() instanceof jQuery; //false jQuery() instanceof jQuery.Set; //true
However, if we install prototype from jQuery to jQuery.Set.prototype , we will see what happens.
jQuery.prototype = jQuery.Set.prototype; jQuery() instanceof jQuery; //true!
It is not easy to understand everything that led to these design decisions, and maybe I miss important points, but for me it seems that their design is too complicated.