Last active
December 28, 2015 07:59
-
-
Save rizalp/7468699 to your computer and use it in GitHub Desktop.
How to do deep copy to Javascript object, and call the parent's own prototype method
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
/* 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