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-

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 = ...

2 Comments

Thanks alot for the explanation- Michael beat you by a hair
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.