Skip to content

Instantly share code, notes, and snippets.

@topliceanu
Created March 6, 2012 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topliceanu/1985835 to your computer and use it in GitHub Desktop.
Save topliceanu/1985835 to your computer and use it in GitHub Desktop.
extends objects, similar in functionality to $.extend or _.extend
// jquery style `extend` work in ES5 compatible envs
var extend = function (obj) {
var args = Array.prototype.slice.call(arguments, 1);
args.forEach( function (source) {
for (var prop in source)
if (source.hasOwnProperty(prop)) obj[prop] = source[prop];
});
return obj;
};
// jquery style `extend` function
var extend = function (obj) {
var args = Array.prototype.slice.call(arguments, 1),
i,k,j, n = args.length, o;
for (i = 0; i < n; i ++) (function (j) {
o = args[i];
for (var k in o)
if (o.hasOwnProperty(k)) (function(key, value) {
obj[key] = value;
})(k, o[k]);
})(i);
return obj;
};
// lightweight recursive extend
var recursiveExtend = function () {
var result = {},
args = Array.prototype.slice.call(arguments),
mergeRecursive = function (obj1, obj2) {
for (var p in obj2) {
try {
if ( obj2[p].constructor==Object ) {
obj1[p] = mergeRecursive(obj1[p], obj2[p]);
}
else {
obj1[p] = obj2[p];
}
}
catch(e) {
obj1[p] = obj2[p];
}
}
return obj1;
};
args.forEach( function (obj) {
mergeRecursive(result, obj);
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment