Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created June 5, 2011 20:30
Show Gist options
  • Save rwaldron/1009387 to your computer and use it in GitHub Desktop.
Save rwaldron/1009387 to your computer and use it in GitHub Desktop.
Real, deep copied objects.
function clone( obj ) {
var val, length, i,
temp = [];
if ( Array.isArray(obj) ) {
for ( i = 0, length = obj.length; i < length; i++ ) {
// Store reference to this array item's value
val = obj[ i ];
// If array item is an object (including arrays), derive new value by cloning
if ( typeof val === "object" ) {
val = clone( val );
}
temp[ i ] = val;
}
return temp;
}
// Create a new object whose prototype is a new, empty object,
// Using the second properties object argument to copy the source properties
return Object.create({}, (function( src ) {
// Initialize a cache for non-inherited properties
var props = {};
Object.getOwnPropertyNames( src ).forEach(function( name ) {
// Store short reference to property descriptor
var descriptor = Object.getOwnPropertyDescriptor( src, name );
// Recurse on properties whose value is an object or array
if ( typeof src[ name ] === "object" ) {
descriptor.value = clone( src[ name ] );
}
props[ name ] = descriptor;
});
return props;
}( obj )));
}
var orig = {
foo: "bar",
inner: {
prop: false,
array: [ 1, 2, 3, 4, 5 ]
}
},
cloned = clone( orig );
console.log(
( cloned.hasOwnProperty("foo") && "PASS" ) || "FAIL", cloned.foo
);
console.log(
( cloned.hasOwnProperty("inner") && "PASS" ) || "FAIL", cloned.inner
);
console.log(
( cloned.inner.hasOwnProperty("prop") && "PASS" ) || "FAIL", cloned.inner.prop
);
console.log(
( cloned.inner.hasOwnProperty("array") && "PASS" ) || "FAIL", cloned.inner.array
);
// Change a value of the original `inner.array`
cloned.inner.array[0] = "a";
console.log(
( orig.inner.array[0] !== cloned.inner.array[0] && "PASS" ) || "FAIL",
orig.inner.array[0],
cloned.inner.array[0]
);
cloned.foo = "qux";
console.log(
( orig.foo !== cloned.foo && "PASS" ) || "FAIL", orig.foo, cloned.foo
);
@rwaldron
Copy link
Author

Demo & tests: http://jsfiddle.net/rwaldron/4SEGz/

Results in console

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment