jQuery has a library of functions stored in an internal object named fn
. These are the ones that you can call on every jQuery object.
When you do $("div.someClass")
you get a jQuery object containing all <div>
elements of that class. Now you can do $("div.someClass").each( someFunction )
to apply someFunction
to each of them. This means, that each()
is one of the functions stored in fn
(a built-in one in this case).
If you extend (add to) the internal fn
object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log()
. You could append this function to $.fn
, and then use it as $("div.someClass").log()
.
Every function appended to the fn
object will be called in such a way that inside the function body, the this
keyword will point to the jQuery object you've used.
Common practice is to return this
at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction )
.
There are several ways to append functions to the $.fn
object, some safer than others. A pretty safe one is to do:
jQuery.fn.extend({
foo: function() {
this.each( function() { console.log(this.tagName); } );
return this;
}
})