jQuery fn.extend ({bla: function(){}} vs. jQuery.fn.bla

Colleen  Kitchen picture Colleen Kitchen · Apr 9, 2010 · Viewed 10.7k times · Source

OK I think I get Difference between jQuery.extend and jQuery.fn.extend?

in that the general extend can extend any object, and that fn.extend is for plugin functions that can be invoked straight off the jquery object with some internal jquery voodoo.

So it appears one would invoke them differently. If you use general extend to extend object obj by adding function y, then the method would attach to that object, obj.y() but if you use fn.extend then they are attach straight to the jquery object $.y().... Have I got that correct yes or no and if no what do I have wrong in my understanding?

Now MY question:

The book I am reading advocates using

jQuery.fn.extend({
    a: function() { },
    b: function() { }
});

syntax but in the docs it says

jQuery.fn.a = function() { };

and I guess if you wanted b as well it would be

jQuery.fn.b = function() { };

Are these functionally and performance-wise equivalent and if not what is the difference?

Thank you very much. I am digging jQuery!

Answer

maček picture maček · Apr 9, 2010

There's very subtle difference between them. Performance wise (not that this is an issue), jQuery.fn.extend is going to be slower than directly declaring a function like jQuery.fn.foo = function(){ };. I'm talking completely negligible difference.

The difference is jQuery.fn.extend() allows you to add multiple plugin functions simultaneously and might make your code look a little cleaner depending on what type of plugin you're authoring.


jQuery.fn.a = function(){};
jQuery.fn.b = function(){};

Is exactly the same as

jQuery.fn.extend({
  a: function(){ },
  b: function(){ }
});