jQuery object constructor – why jQuery.fn.init.prototype = jQuery.fn

Whenever you dig into the sources of jQuery, it kind of feels intriguing – why its prototype is written in such a weird manner:

jQuery.fn = jQuery.prototype = {...}
//and somewhere else in the code

var init = jQuery.fn.init = function( selector, context ) {...}

I mean, fn is a shorthand for function,and generally people use it to wrap all methods (private or public is at the discretion of the programmer/architect).

I found a very interesting article pertinent to jQuery development and that is as follows

Michael Geary (Google groups discussion thread)

jQuery.fn is one of those things that exists mainly for historical reasons. In the very first versions of jQuery, $.fn was not the same as $.prototype.

There was no jQuery object by that name in those days, just a $ object.

$.prototype wasn’t used for anything; instead, every time a jQuery object was created, all of the method references found in $.fn were copied, one by one, into the new jQuery object.

As you can guess, this was a bit slow, and I came up with a patch to use $.prototype in the conventional manner instead of copying all the methods.

$.fn was kept as an alias of $.prototype for compatibility with existing plugins that already used $.fn.

So, the code:

jQuery.fn.init.prototype = jQuery.fn;

could be written:

jQuery.prototype.init.prototype = jQuery.prototype;

What does that do?

It gives the init() function the same prototype as the jQuery object.

So when you call init() as a constructor in the “return new jQuery.fn.init( selector, context );” statement, it uses that prototype for the object it constructs. This lets init() substitute for the jQuery constructor itself.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s