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);
}
Reading the relevant jQuery source file
The first aregument sent to
jQuery.extendis used. If it is falsy or undefined, a new empty object will be created.targetis then returned byjquery.extend.If you were to do the following:
targetwould still beundefined. If you want to work with atargetthat may be undefined, you have to usejQuery.extendlike so:Working off your example code, you need to do this:
Note how the return value of
jQuery.extendis assigned tooptions.data.