frogatto
frogatto

Reputation: 29285

Structure of most jQuery plugins

Why most jQuery plugins are based on structure:

(function($)
{
    // do stuff with $
})(jQuery)

I think this structure is equivalence with this plain structure:

// do stuff with object 'jQuery'

As i think the 1st structure defines a function and call it with input parameter jQuery, Why we should do this, We can ignore the function and execute our code with object jQuery without any additional function
Can someone tell me why the 1st structure is better and more be used?

Upvotes: 0

Views: 49

Answers (2)

cobbal
cobbal

Reputation: 70743

It is (almost entirely) equivalent. The reason to do this is mostly convenience, it's a pain to write out jQuery every single time, and it's less idiomatic than just using $. There's a problem, however: many other popular javascript libraries use a $ function, so jQuery can be loaded in "no conflict" mode where it doesn't set the global variable $. In order for plugins to reference it in either no-conflict or normal mode, they include wrapping it in a function as you noticed.

As a side benefit, any var statements inside the "do stuff" region become function local, instead of global.

Upvotes: 1

Pieter
Pieter

Reputation: 1833

The (function($) { and })(jQuery) parts are meant to keep variables savely inside the function to avoid conflicts with other code or other plugins.

A plugin function is defined like this:

(function($) {

    $.fn.do_stuff = function() {

        //Do stuff

    }

})(jQuery);

Upvotes: 2

Related Questions