tags:

views:

46

answers:

1

Hi,

my question is when do i should use $.extend(...) ?
In many jquery plugins i see that the jquery-object itself is extended with new (global) functions:

$.extend({
    doSth: function() {
        alert('do sth here');
    }
}

What are the advantages of extending the jquery-object instead of creating a global object containing the function:

var myLib = {
    doSth: function() {
        alert('do sth here');
    }
}

Currently i am developing a small js-lib. In that lib the $.fn-object is extended and i need some global functions.
But i don't know where to put the global functions: in my own lib-object or in the jquery-object?

Best Regards,
Biggie

+2  A: 

To give some context since it's not entirely clear from the question: For those unaware, $.extend() with a single parameter extends the jQuery object.


Often there is no need for this, unless you're adding something very library related, I'd keep it in your own namespace. It serves no purpose under $ and the only possible thing that can happen is a potential naming conflict later with new jQuery core updates.

If you have one or two static methods that go with a plugin, where you're extending both $.fn and $ then I'd see it as acceptable, but if you have many methods (which sounds like the case) there's no real benefit to them being on $.

Honestly the reason the single argument versions exists (or, more accurately, was added in the first place) is for jQuery itself, for internal usage (pretty much every "section" uses it, check it out here, here and here as examples), I'm not sure that external uses were ever intended, they just left it open/extensible for that.

Nick Craver
"the reason the single argument versions exists is for jQuery itself" -- and for plugins as well.
lonesomeday
@lonesomeday - Not really, the reason it was *added* was for jQuery, though plugins *can* use it, most plugins will extend `jQuery.fn`, *not* jQuery, plugins don't *need* their static functions on the jQuery object, they do however *have* to be on `$.fn` to be used in chains.
Nick Craver
Sorry, was getting ahead of myself.
lonesomeday
@lonesomeday - It's a valid point, I updated to hopefully address it more clearly, I see how you could read it that way....hopefully clearer now :)
Nick Craver