Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use $.extend({...})?

Tags:

jquery

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

like image 746
Biggie Avatar asked Oct 06 '10 11:10

Biggie


1 Answers

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.

like image 137
Nick Craver Avatar answered Nov 02 '22 17:11

Nick Craver