Last active
August 29, 2015 14:02
-
-
Save Williammer/ff58e9204054fc0b76e6 to your computer and use it in GitHub Desktop.
jsPatterns.deepExtendObject.js - deeply copy property from the parent. (merely the object property)
This file contains hidden or 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
| function extendDeep(parent, child) { | |
| var i, | |
| toStr = Object.prototype.toString, | |
| astr = "[object Array]"; | |
| child = child || {}; | |
| for (i in parent) { | |
| if (parent.hasOwnProperty(i)) { | |
| if (typeof parent[i] === "object") { | |
| child[i] = (toStr.call(parent[i]) === astr) ? [] : {}; | |
| extendDeep(parent[i], child[i]); | |
| } else { | |
| child[i] = parent[i]; | |
| } | |
| } | |
| } | |
| return child; | |
| } | |
| var dad = { | |
| counts: [1, 2, 3], | |
| reads: { | |
| paper: true | |
| } | |
| }; | |
| var kid = extendDeep(dad); | |
| kid.counts.push(4); | |
| kid.counts.toString(); // "1,2,3,4" | |
| dad.counts.toString(); // "1,2,3" | |
| dad.reads === kid.reads; // false | |
| kid.reads.paper = false; | |
| kid.reads.web = true; | |
| document.body.innerHTML = dad.reads.paper; // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment