Difference between jQuery.extend and jQuery.fn.extend? Difference between jQuery.extend and jQuery.fn.extend? jquery jquery

Difference between jQuery.extend and jQuery.fn.extend?


jQuery.extend is used to extend any object with additional functions, but jQuery.fn.extend is used to extend the jQuery.fn object, which in fact adds several plugin functions in one go (instead of assigning each function separately).

jQuery.extend:

var obj = { x: function() {} }jQuery.extend(obj, { y: function() {} });// now obj is an object with functions x and y

jQuery.fn.extend:

jQuery.fn.extend( {        x: function() {},        y: function() {}});// creates 2 plugin functions (x and y)


jQuery.extend({    abc: function(){        alert('abc');    }});

usage: $.abc(). (No selector required like $.ajax().)

jQuery.fn.extend({    xyz: function(){        alert('xyz');    }});

usage: $('.selector').xyz(). (Selector required like $('#button').click().)

Mainly it is used to implement $.fn.each().

I hope it helps.


Difference between jQuery.extend and jQuery.fn.extend?

Actually, there is none apart from their base reference. In the jQuery source, you can read:

jQuery.extend = jQuery.fn.extend = function() { … };

So how does it work? The documentation reads:

Merges the contents of two or more objects together into the first object.

It's just a for-in-loop that copies properties, pimped up with a flag to recurse nested objects. And another feature:

If only one argument is supplied to $.extend(), this means the target argument was omitted

 // then the following will happen: target = this;

So if the function is called on jQuery itself (without explicit target), it will extend the jQuery namespace. And if the function is called on jQuery.fn (without explicit target), it will extend the jQuery prototype object where all the (plugin) methods are located.