Skip to content

Instantly share code, notes, and snippets.

@AverageMarcus
Created June 14, 2014 19:54
Show Gist options
  • Save AverageMarcus/6ab6fbc57fe97be91c7a to your computer and use it in GitHub Desktop.
Save AverageMarcus/6ab6fbc57fe97be91c7a to your computer and use it in GitHub Desktop.
Extends an object with values from another object. Existing properties are ignored. Useful for ensuring options have default values.
Object.prototype.extend = function(obj){
if(typeof obj !== 'object') return this;
var current, prop,
i = 0,
length = arguments.length;
for(; i<length; i++){
current = arguments[i];
if(typeof current === 'object'){
for(prop in current){
if(!this[prop]){
this[prop] = current[prop];
}
}
}else{
console.warn("Input variables should be objects, ignoring.");
}
}
return this;
};
@AverageMarcus
Copy link
Author

Example:

/*
userOptions = {
  width : 500
}
*/
function doSomething(userOptions){
  var options = {
    height : 100,
    width : 100
  };

  options = userOptions.extend(options);
  /*
    options = { 
      height : 100,
      width : 500
    }
  */
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment