Created
August 9, 2011 18:56
-
-
Save addyosmani/1134878 to your computer and use it in GitHub Desktop.
Some random fun with object cloning
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
/* | |
* objectClone.js (c) Addy Osmani, 2011. | |
* Do whatever license. | |
* Thanks to gf3 and ben_alman for tips that helped improve. | |
*/ | |
function objectClone(q){ | |
var n = (q instanceof Array) ? [] : {},i; | |
for (i in q) { | |
if (Object.prototype.toString.call({}) == Object.prototype.toString.call( q[i] )) { | |
n[i] = objectClone(q[i]); | |
} else n[i] = q[i] | |
} return n; | |
}; | |
/*usage*/ | |
var obj = { omg: 'wtf', sexypants : 'mikeyface', tester:function(){ console.log('ZOMGAH');}}; | |
var test = objectClone(obj); | |
console.log(obj); | |
console.log(test); | |
test.p = 'lalalalalala'; | |
test.magic = function(){ | |
console.log('magicalness'); | |
} | |
test.tester(); | |
console.log(test); | |
var testArray = ['beans','beans','the','magical','fruit']; | |
var testObj = objectClone(testArray); | |
console.log(testArray); | |
console.log(testObj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment