Why are these two ways of writing a jQuery plugin equivalents?

javascript, jquery, jquery-plugins

Solution

Let's reduce from one to the other:

$.fn.myplugin = function () {
    return $(this).each(function() {
        return $(this).bind('click', function () {
            console.log('Hi');
        });
    });
};

When you start your function `this` is a jQuery object, so `$(this)` doesn't buy you anything, it could easily become:

$.fn.myplugin = function () {
    return this.each(function() {
        return $(this).bind('click', function () {
            console.log('Hi');
        });
    });
};

So you are saying "For each element in the jQuery object, create a jQuery object and bind an event to that object."

If you look in `bind`, it calls `on`, which performs some logic and finally does this line:

return this.each( function() {
    jQuery.event.add( this, types, fn, data, selector );
});

That means it is going to apply the event to every element in that jQuery object, so you are actually saying:

So you are saying "For each element in the jQuery object, create a jQuery object, and for every element in that jQuery object bind an event to that element."

You are now looping twice, once in a list of `N` elements and then `N` times in lists of 1 element. You can actually just all bind directly:

$.fn.myplugin = function () {
    return this.bind('click', function () {
        console.log('Hi2');
    });
};

And that of course, is the final code.

Problem

Why are these two ways of writing a jQuery plugin equivalents? First way: ``` $.fn.myplugin = function () { return $(this).each(function() { return $(this).bind('click', function () { console.log('Hi'); }); }); }; ``` Second way: ``` $.fn.myplugin = function () { return this.bind('click', function () { console.log('Hi2'); }); }; ```

Original source