Created
December 19, 2014 20:13
-
-
Save lot224/a5dbe06e77ce9a4e9f50 to your computer and use it in GitHub Desktop.
simple javascript extend function
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
var extend = function () { | |
if (arguments.length == 0) | |
return {}; | |
if (arguments.length == 1) | |
return arguments[0]; | |
var nResult = {}; | |
for (var i = 0; i < arguments.length; i++) { | |
var source = arguments[i]; | |
for (var prop in source) { | |
if (typeof source[prop] === "object" && source[prop] !== null) { | |
nResult[prop] = extend(nResult[prop] || {}, source[prop]); | |
} else { | |
nResult[prop] = source[prop]; | |
} | |
} | |
} | |
return nResult; | |
}; | |
var obj1 = { prop1: "abc", prop2: { subProp1: 123, subProp2:456 } }; | |
var obj2 = { prop2: { subProp1: 321, subProp3: 789 }, prop3: 'def' }; | |
var obj3 = { prop4: 'hij'}; | |
var nResult = extend(obj1, obj2, obj3); | |
console.log(nResult); | |
/* | |
{ prop1: 'abc', prop2: { subProp1: 321, subProp2: 456, subProp3: 789 }, prop3: 'def', prop4: 'hij' } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment