Skip to content

Instantly share code, notes, and snippets.

@stolsma
Forked from polotek/clone.js
Created September 25, 2011 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stolsma/1240958 to your computer and use it in GitHub Desktop.
Save stolsma/1240958 to your computer and use it in GitHub Desktop.
Real, deep copied objects.
function hasOwnProperty(key) {
if(this[key]) {
var proto = this.prototype;
if(proto) {
return ((key in this.prototype) && (this[key] === this.prototype[key]));
}
return true;
} else {
return false;
}
}
if(!Object.prototype.hasOwnProperty) { Object.prototype.hasOwnProperty = hasOwnProperty; }
function create(o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
}
if(!Object.create) { Object.create = create; }
function isArray( obj ) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
if(!Array.isArray) { Array.isArray = isArray; }
function clone( obj ) {
if ( Array.isArray( obj ) ) {
return [].slice.call( obj, 0 );
}
// Create a new object whose prototype is a new, empty object,
// Using the second propertiesObject argument to copy the source properties
return Object.create({}, (function(src) {
var props = Object.getOwnPropertyNames( src ),
dest = {};
props.forEach(function( name ) {
var descriptor = Object.getOwnPropertyDescriptor( src, name ),
tmp;
// Recurse on properties whose value is an object or array
if ( typeof src[ name ] === "object" ) {
descriptor.value = clone( src[ name ] );
}
dest[ name ] = descriptor;
});
return dest;
})( obj ));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment