Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Created August 9, 2011 18:56
Show Gist options
  • Save addyosmani/1134878 to your computer and use it in GitHub Desktop.
Save addyosmani/1134878 to your computer and use it in GitHub Desktop.
Some random fun with object cloning
/*
* 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