Cloning a JavaScript Object Using jQuery

I was recently using Keith Wood’s calendar plugin and kept running into an issue when trying to copy a date object and add days to it. When I would copy the object, I was actually just creating a reference to the original… Not what I wanted.

Found the answer was to clone the object, and John Resig had the answer via jQuery’s $.extend() method. It’s awesome when your fav lib has the method you need so writing one from scratch isn’t necessary. Check it out:

cfg = {};
cfg.c = { 'inst' : j.calendars.instance() };
var func = function(s){
	cfg.c.start = typeof s === 'string' && s.length > 0 ? cfg.c.inst.parseDate('mm/dd/yyyy',s) : cfg.c.inst.today();
	cfg.c.end = j.extend({},cfg.c.start); // clone so we're not updating cfg.c.start via reference
};

Leave a Reply

Your email address will not be published. Required fields are marked *