Created
March 6, 2012 11:43
-
-
Save topliceanu/1985835 to your computer and use it in GitHub Desktop.
extends objects, similar in functionality to $.extend or _.extend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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