Skip to content

Instantly share code, notes, and snippets.

@daniel-williams
Created April 10, 2015 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-williams/78ff3eb66a79c001ed74 to your computer and use it in GitHub Desktop.
Save daniel-williams/78ff3eb66a79c001ed74 to your computer and use it in GitHub Desktop.
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
// smashless version
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
// jQuery?
// merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
// now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }
// smashless
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
/* merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);
// the content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// defaults and options variable remained the same
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment