Skip to content

Instantly share code, notes, and snippets.

@sivagao
Created April 14, 2013 07:38
Show Gist options
  • Select an option

  • Save sivagao/5381818 to your computer and use it in GitHub Desktop.

Select an option

Save sivagao/5381818 to your computer and use it in GitHub Desktop.
JS:Utility-objectclone[140byte].js
<!DOCTYPE html>
<title>Foo</title>
<script>
function c(a){var b=a instanceof Array?[]:{},d,e=Object.prototype.toString;for(d in a)b[d]=e.call({})==e.call(a[d])?c(a[d]):a[d];return b}
/*test cloning*/
var obj = { omg: 'wow', sexypants : 'mikeyface', tester:function(){ console.log('ZOMGAH');}},
test = c(obj);
console.log(obj);
console.log(test);
/*test direct assignment, followed by cloning*/
test.p = 'lalalalalala';
test.magic = function(){
console.log('magicalness');
}
test.tester();
console.log(test);
/*test passing arrays through the cloner*/
var testArray = ['beans','beans','the','magical','fruit'],
testObj = c(testArray);
console.log(testArray);
console.log(testObj);
</script>
<!-- "description": "A compact object cloning routine.", -->
<script>
/*
* objectClone.js (c) Addy Osmani, 2011.
* Do whatever license.
* Thanks to gf3 and ben_alman for tips that helped improve.
*/
function objectClone(q) {
/*determine if the object is an instance of a known object type (array).if an array, instantiate n as an array*/
var n = (q instanceof Array) ? [] : {},
i;
/*iterate through the input*/
for (i in q) {
/*Object.prototype.toString is a ref to Object.prototype so the results [object Object] will result despite argument supplied. call() however sets toString's 'this' keyword as a ref to the passed input (eg. [object Array]) allowing us to accurately handle different types of input*/
if (Object.prototype.toString.call({}) == Object.prototype.toString.call(q[i])) {
/*if an object, set n to a clone of q[i]*/
n[i] = objectClone(q[i]);
/*otherwise, simply map n[i] to q[i] (eg. for arrays)*/
} else n[i] = q[i]
}
return n;
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment