I saw this in a plugin:
var options = $.extend(defaults, options);
How does it work?
What does extend() do?
The documentation isn't precise in explaining how extend works, so I ran a little test:
var a = {foo: 1, bar: 1};
var b = {foo: 2, baz: 2};
var c = {foo: 3};
var r = jQuery.extend(a,b,c);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar + " Baz=" + a.baz);
console.log("B: Foo=" + b.foo + " Bar=" + b.bar + " Baz=" + b.baz);
console.log("C: Foo=" + c.foo + " Bar=" + c.bar + " Baz=" + c.baz);
console.log("R: Foo=" + r.foo + " Bar=" + r.bar + " Baz=" + r.baz);
console.log("A === R?: " + (a === r));
(The console.log function is intended to work in Firebug; replace it with alert() or some other output function if you like).
The results are:
A: Foo=3 Bar=1 Baz=2
B: Foo=2 Bar=undefined Baz=2
C: Foo=3 Bar=undefined Baz=undefined
R: Foo=3 Bar=1 Baz=2
A === R?: true
By this we can see that jQuery.extend():
This is useful for combining user and default option-objects together to get a complete set of options:
function foo(userOptions) {
var defaultOptions = {
foo: 2,
bar: 2
};
var someOtherDefaultOptions = {
baz: 3
};
var allOptions = jQuery.extend(
defaultOptions,
someOtherDefaultOptions,
userOptions
);
doSomething(allOptions);
}
foo({foo:1, baz:1});
Note that "null" is a valid value for overwriting, but "undefined" isn't. You might be able to make use of this.
var a = {foo: "a", bar: "a"};
var b = {foo: null, bar: undefined};
jQuery.extend(a,b);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar);
Results in:
A: Foo=null Bar=a
If you pass just one object to jQuery.extend(), then jQuery assumes that the jQuery object itself is the "first" parameter (ie: the one to be modified), and your object is the "second" (ie: the one to add to the first). So:
console.log( "Before: " + jQuery.foo );
jQuery.extend({foo:1});
console.log( "After: " + jQuery.foo );
Results in:
Before: undefined
After: 1