Skip to content

Instantly share code, notes, and snippets.

@hectormenendez
Created March 20, 2012 07:16
Show Gist options
  • Save hectormenendez/2132385 to your computer and use it in GitHub Desktop.
Save hectormenendez/2132385 to your computer and use it in GitHub Desktop.
Simple extend.
/**
* Extends old object with new (returns a copy)
*
* @author Hector Menendez <[email protected]>
* @created 2011/NOV/21 17:41
* @updated 2012/MAR/20 01:13 Added support for unlimited arguments.
* Native properties will be ignored.
*/
core.extend = function(){
var args = private.arguments(arguments); // sanitize args
if (!args.length) return core.error('Missing objects to extend','extend');
// first argument will be considered the original, we won't rewrite it.
var orig = args.shift();
if (typeof orig != 'object')
return core.error('First argument needs to be an object.','extend');
var i,prop;
for (i in args){
if (typeof args[i] != 'object')
return core.error('All arguments need to be objects.','extend');
// traverse properties of each object argument and copy them.
for (prop in args[i]){
if (!args[i].hasOwnProperty(prop)) continue; // ignore native props
orig[prop] = args[i][prop];
}
}
// make a copy of original object
var copy = {};
for (i in orig) {
if (!orig.hasOwnProperty(i)) continue; // ignore native props
copy[i] = orig[i];
}
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment