There is a significant difference between using .extend() with one argument and doing it with two or more:
When .extend() receives a single object, it adds the methods defined in it to either the jQuery or the jQuery.fn (also called jQuery.prototype and $.fn) objects.
As a general rule, you should extend the jQuery object for functions and the jQuery.fn object for methods. A function, as opposed to a method, is not accessed directly from the DOM.
Notice the different way of calling a method when extending the jQuery.fn or jQuery objects. The receiver (what’s left of the period) changes.
$.fn.extend({
myMethod: function(){...}
});
//jQuery("div").myMethod();
$.extend({
myMethod2: function(){...}
});
//jQuery.myMethod();
When .extend() receives two or more objects, it takes the first object and adds to it the methods and variables defined in the other objects. See an example:
defaults = { size: 3 };
options = { height: 6 };
var opts = $.extend(defaults, options)
// 'defaults' receives the methods and variables defined in 'options'
// opts == defaults == { size: 3, height: 6 }
// options == { height: 6 };
If the first object is empty, it will add the methods and variables in a new object. This is useful when we want to group the methods defined in several objects without modifying any of them:
<pre>var opts = $.extend( {}, defaults, options)
// 'opts' gets all methods and variables defined in 'defaults' and 'options',
// neither of them get modified.
// opts == { size: 3, height: 6 }
// defaults == { size: 3 };
// options == { height: 6 };
9 responses so far ↓
Alok Shukla // 15 January, 2009 at 12:38 pm |
Excellent post!!
I had too much confusion while using extend and after reading this its very clear.
Thanks a lot!!
webdevvote // 2 March, 2009 at 11:14 am |
You are voted!
Track back from http://webdevvote.com
recursive object merge with $.extend() « MENINMAC // 1 April, 2009 at 8:28 pm |
[...] This post comes as an addition to this article: http://asimilia.wordpress.com/2008/12/17/jquery-extend-confusion/ [...]
Marcos // 6 April, 2009 at 4:08 pm |
Excelent Explication!!!
It takes my doubts!
Thanks.
Joniba // 11 May, 2009 at 9:41 am |
Adding my thanks to you about this confusing topic!
Shiva // 11 June, 2009 at 3:48 pm |
Thanks so much for your article. I found your explanation and snapshots helpful.
Karl Oakes // 27 June, 2009 at 6:35 pm |
Thanks for the explanation.. so $.extend({method:function(){}) is similar to a static method with no instance required and therefore not chainable.
While $.fn.extend(method:function(){return this…}) is similar to an instance method with an implied instance that is chainable due to the return this.
Julian Johannesen // 28 July, 2009 at 1:03 am |
Thanks so much. This was very helpful.
Guek // 16 October, 2009 at 3:18 am |
Thanks you.. really help me a lot..