When you do something like var el = $("#content");
, you're dealing with a few different types of objects:
- Strings.
"#content"
. 'Nuff said.
- Functions.
$
(here, a synonym for jQuery
) is a function. You're calling it with the string "#content"
, as we established above.
- jQuery objects. The
jQuery
function creates jQuery objects. el
is one of those objects.
The jQuery
function and its direct attached properties are mostly things that don't apply to any particular element; they're things you might want to do on their own. Take, for example, jQuery.ajax
; that doesn't apply to an element, so it was put directly on the jQuery
function.
Other functionality only makes sense when you've got the context of what elements to apply the operation to. Say, for example, removing a class. If I say jQuery.removeClass("selected");
, what do I want to remove the class from? You never specified, so you can't do that. Instead, assuming we assigned el
as above, el.removeClass("selected");
does indeed make some sense; it removes a class from whatever elements el
represents (here, the element with an ID of content
).
Whenever we have one of these function names after the dot, it's a property of something before the dot (either directly or indirectly). In the case of functions like ajax
where no elements are involved, it's put directly on $
/jQuery
. In the case of methods like removeClass
, it's put on all jQuery
objects.
Of course, if you ever want to add a new method that can be used on a set of elements like removeClass
, it would be rather tedious to add that property to every single one, let alone the issue of getting a reference to every jQuery object, past, present, and future! For that reason, jQuery.fn
is an object that acts as the prototype of all jQuery objects. That means that whenever you create a new jQuery object, it will act minimally like the prototype it was based on, jQuery.fn
. If you add a property to jQuery.fn
, it will appear on all jQuery objects. In fact, the concept of a prototype is deeply embedded into JavaScript, and modifying jQuery.fn
will affect all jQuery objects, whether they're newly created, created in the past, or created in the future.