tags:

views:

70

answers:

1

Following jQuery does not change the value of defaults or options. The returned value is same as empty. empty has been changed and populated with merged data. All is good.

var empty = {} 
var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
$.extend(empty, defaults, options);

However I saw someone passing true as the first option.

var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" };  
var output = $.extend(true, defaults, options);

In this case defaults has been changed.options is same and the returned value is same as defaults.

Now try passing false.

var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
var output = $.extend(false, defaults, options);

In this case defaults and options are not changed. So passing true is same as

var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
var output = $.extend(defaults, options);
+1  A: 

This is the expected behavior. When you pass in true as the first argument, that means to make a deep copy, rather than sharing object structure. The next argument, defaults becomes the target by the inclusion of the optional boolean deep copy parameter when that parameter is true. Here's the relevant snippet from 1.3.2:

// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

// Handle a deep copy situation
if ( typeof target === "boolean" ) {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
}

When you specify false, you can see that it implicitly constructs a new object which will be the target. This target will be a deep copy of both the following objects.

This is documented in the options to the extend function.

tvanfosson
I use this tool to see the documentation. http://view.jquery.com/trunk/tools/api-browser/#link-jQueryextend-targetobject1objectN Now it seems the url I used to look at is either stale or has only half information.Thanks. I will start referring to the main jQuery doc.
Neeraj Singh