Skip to content

Instantly share code, notes, and snippets.

@rizalp rizalp/DeepCopy.js
Last active Dec 28, 2015

Embed
What would you like to do?
How to do deep copy to Javascript object, and call the parent's own prototype method
/* Title: Deep Copy Object Properties
* Refference: https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/inheritance-by-copying-properties.html
* Description: an object gets functionality from another object, simply by copying it
* Only the properties will be copied. The prototype will not
* it is generally not recomended to copy the prototype over
*/
/* deep copy */
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]; //primitive value can be copied over
}
}
}
return child;
}
function Man() {
this.counts = [1,2,3];
this.reads = {paper: true};
}
Man.prototype.slapChild = "Slap!";
Man.prototype.counting = function() {
return "current counts from this is " + this.counts;
}
var dad = new Man();
var kid = extendDeep(dad);
kid.counts.push(400);
kid.counts; // [1,2,3,400]
dad.counts; // [1,2,3]
dad.slapChild; // "Slap!"
kid.slapChild; //undefined
dad.reads === kid.reads; // false. Both aren't refferencing to the same object
//now, what if we would like to call the prototype method from dad?
dad.constructor.prototype.counting.call(kid); // "current counts from this is 1,2,3,400"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.