jQuery in Action
200
CHAPTER 7
Extending jQuery with custom plugins
Within the body of the method, the function context (
this
) refers to the wrapped 
set. We can use all of the predefined jQuery commands on it; as in this example, 
we call the
we call the
css()
 command on the wrapped set to set the 
color
 to 
blue
 for all 
matched 
DOM
 elements.
WARNING
The function context (
this
) within the main body of a wrapper method 
refers to the wrapped set, but when inline functions are declared within 
this function, they each have their own function contexts. You must take
care when using
this function, they each have their own function contexts. You must take
care when using
this
 under such circumstances to make sure that it's 
referring to what you think it is! For example, if you use 
each()
 with its 
iterator function, 
this
 within the iterator function references the 
DOM
element for the current iteration.
We can do almost anything we like to the 
DOM
 elements in the wrapped set, but 
there is one very important rule when defining new wrapper methods; unless the 
function is intended to return a specific value, it should always return the wrapped
set as its return value. This allows our new command to take part in any jQuery
command chains. In our example, because the
function is intended to return a specific value, it should always return the wrapped
set as its return value. This allows our new command to take part in any jQuery
command chains. In our example, because the
css()
 command returns the 
wrapped set, we simply return the result of the call to 
css()
.
 In this example, we apply the jQuery 
css()
 command to all the elements in 
the wrapped set by applying it to 
this
. If, for some reason, we need to deal with 
each wrapped element individually (perhaps because we need to make condi-
tional processing decisions), the following pattern can be used:
tional processing decisions), the following pattern can be used:
(function($){
  $.fn.someNewMethod = function() {
    return this.each(function(){
      //
      // Function body goes here -- this refers to individual
      // elements
      //
    });
  }
})(jQuery);
In this pattern, the 
each()
 command is used to iterate over every individual ele-
ment in the wrapped set. Note that, within the iterator function, 
this
 refers to the 
current 
DOM
 element rather than the entire wrapped set. The wrapped set 
returned by 
each()
 is returned as the new method's value so that this method can 
participate in chaining.