westlywright
westlywright

Reputation: 75

Does jQuery Extend Create an Empty Object when Target is Undefined

Working with the jQuery extend functionality and have run into a case where I am trying to extend a target object that is undefined. I don't get any errors but the source object is not extended as expected. I had assumed that jQuery would create a blank object and extend to that but this does not seem to be the case. I can work around this by creating the empty object my self but I am looking for some confirmation that this is the case with jQuery's extend. I could not find anything in the jQuery Api about the target object being undefined.

EDIT: Sorry I should have included a JSFiddle - Here or see the example below. And in doing so need to modify my question. If you look in the fiddle the options object exists, but the property I'm trying to extend to does not exist. This is where my problem is lying. I am guessing jQuery won't create the empty property this way. And I would need to add the property to the object manually?

options = {newdata:true};

$("#click").click(function(){
  console.log(options);
  someFunc(options);
});

function someFunc(options) {
  $.extend(options.data, {
    someNewData: true
  });
  console.log(options);
}

Upvotes: 0

Views: 984

Answers (1)

Tim Heap
Tim Heap

Reputation: 1711

Reading the relevant jQuery source file

target = arguments[0] || {};

The first aregument sent to jQuery.extend is used. If it is falsy or undefined, a new empty object will be created. target is then returned by jquery.extend.

If you were to do the following:

var target = undefined;
var data = {'hello': 'world'};
jQuery.extend(target, data);

target would still be undefined. If you want to work with a target that may be undefined, you have to use jQuery.extend like so:

var target = undefined;
var data = {'hello': 'world'};
target = jQuery.extend(target, data);

Working off your example code, you need to do this:

function someFunc(options) {
    options.data = $.extend(options.data, {
        someNewData: true
    });
    console.log(options);
}

Note how the return value of jQuery.extend is assigned to options.data.

Upvotes: 1

Related Questions