2

According to the jQuery plugin authoring guidelines, a basic plugin structure would look like this:

(function($){

  $.fn.myPlugin = function( options ) {  

    return this.each(function() {

      // Do something...

    });
  };
})( jQuery );

Yet I've seen the following pattern in several jQuery plugins I've inspected:

(function($){
        $.extend($.fn, {
            myPlugin: function( options ) {

                $(this).each( function() {
                    // Do something
                });
        },
    })
})(jQuery);

Can someone explain the second approach- What is $.extend(... and the object-notation all about?

Thanks-

Yarin
  • 159,198
  • 144
  • 384
  • 498

2 Answers2

4

These two are basically accomplishing the same task, but in a slightly different manner.

$.fn.myPlugin = … is directly assigning the function to the place you want it in the jQuery namespace.

$.extend($.fn, {myPlugin:… is extending the $.fn object with the object specified as the second parameter. In this case, the object simply contains a single property, myPlugin, which is the function to add.

You can use either structure, although I personally find the first a bit cleaner.

Michael Mior
  • 27,152
  • 8
  • 85
  • 111
2

The $.extend function is used to:

Merge the contents of two or more objects together into the first object.

So this:

$.extend($.fn, { ... });

Is just merging the contents of the object literal into $.fn. Using $.extend like this just really just another way of doing the normal/standard assignment:

$.fn.myPlugin = ...
mu is too short
  • 413,090
  • 67
  • 810
  • 771
  • Thanks alot for the explanation- Michael beat you by a hair – Yarin Jul 04 '11 at 22:35
  • @Yarin: That's cool, I mostly wanted to get the link to the official `$.extend` docs through. And yes, the direct assignment is a lot cleaner (IMHO, YMMV, etc). – mu is too short Jul 04 '11 at 22:41