Exactly clone an object in javascript Exactly clone an object in javascript javascript javascript

Exactly clone an object in javascript


jQuery.extend is not expecting you to use the instanceof operator. It is doing a gloriously complicated copy, and not a true clone. Looping through the elements is not enough. Also, calling the constructor isn't best cause you'll loose your arguments. Try this:

var MyClass = function(param1, param2) {    alert(param1.a + param2.a);    this.p1 = param1;    this.p2 = param2;};function Clone() { }function clone(obj) {    Clone.prototype = obj;    return new Clone();}var myObj = new MyClass({a: 1},{a: 2});var myObjClone = clone(myObj);alert(myObj instanceof MyClass);      // => truealert(myObjClone instanceof MyClass); // => trueconsole.log(myObj);       //note they areconsole.log(myObjClone)   //exactly the same

Be aware that since your prototype now points back to the origional (myObj), any changes to myObj will reflect in myObjClone. Javascript's prototypal inheritance is kinda tricky. You need to be sure that your new object has the correct prototype, and hence the correct constructor.

Admitadly, Javascript makes my head hurt. Still, I think I'm reading this right, from the ECMAScript language spec:

13.2.2 [[Construct]]
When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:

  1. Let obj be a newly created native ECMAScript object.
  2. Set all the internal methods of obj as specified in 8.12.
  3. Set the [[Class]] internal property of obj to "Object".
  4. Set the [[Extensible]] internal property of obj to true.
  5. Let proto be the value of calling the [[Get]] internal property of F with argument >"prototype".
  6. If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.
  7. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the >standard built-in Object prototype object as described in 15.2.4.
  8. Let result be the result of calling the [[Call]] internal property of F, providing >obj as the this value and providing the argument list passed into [[Construct]] as args.
  9. If Type(result) is Object then return result.
  10. Return obj.

This person seems to understand the concept much better than I do. K, I'm going back to java now where I swim more than I sink :) .


Have you considered using the clone function suggested here?

function clone(obj){    if(obj == null || typeof(obj) != 'object'){        return obj;    }    var temp = new obj.constructor();    for(var key in obj){        temp[key] = clone(obj[key]);    }    return temp;}var MyClass = function(param1, param2) {};var myObj = new MyClass(1,2);var myObjClone = clone(myObj);alert(myObj instanceof MyClass);      // => truealert(myObjClone instanceof MyClass); // => true


After taking inspiration from some answers I've found on StackOverflow, I've come up with a function that is quite flexible, and still works when the object or any of its sub-objects has a constructor with required parameters (thanks to Object.create).

(Thanks to Justin McCandless this now supports cyclic references as well.)

//If Object.create isn't already defined, we just do the simple shim, without the second argument,//since that's all we need herevar object_create = Object.create;if (typeof object_create !== 'function') {    object_create = function(o) {        function F() {}        F.prototype = o;        return new F();    };}/** * Deep copy an object (make copies of all its object properties, sub-properties, etc.) * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone * that doesn't break if the constructor has required parameters *  * It also borrows some code from http://stackoverflow.com/a/11621004/560114 */ function deepCopy(src, /* INTERNAL */ _visited, _copiesVisited) {    if(src === null || typeof(src) !== 'object'){        return src;    }    //Honor native/custom clone methods    if(typeof src.clone == 'function'){        return src.clone(true);    }    //Special cases:    //Date    if(src instanceof Date){        return new Date(src.getTime());    }    //RegExp    if(src instanceof RegExp){        return new RegExp(src);    }    //DOM Element    if(src.nodeType && typeof src.cloneNode == 'function'){        return src.cloneNode(true);    }    // Initialize the visited objects arrays if needed.    // This is used to detect cyclic references.    if (_visited === undefined){        _visited = [];        _copiesVisited = [];    }    // Check if this object has already been visited    var i, len = _visited.length;    for (i = 0; i < len; i++) {        // If so, get the copy we already made        if (src === _visited[i]) {            return _copiesVisited[i];        }    }    //Array    if (Object.prototype.toString.call(src) == '[object Array]') {        //[].slice() by itself would soft clone        var ret = src.slice();        //add it to the visited array        _visited.push(src);        _copiesVisited.push(ret);        var i = ret.length;        while (i--) {            ret[i] = deepCopy(ret[i], _visited, _copiesVisited);        }        return ret;    }    //If we've reached here, we have a regular object    //make sure the returned object has the same prototype as the original    var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);    if (!proto) {        proto = src.constructor.prototype; //this line would probably only be reached by very old browsers     }    var dest = object_create(proto);    //add this object to the visited array    _visited.push(src);    _copiesVisited.push(dest);    for (var key in src) {        //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.        //For an example of how this could be modified to do so, see the singleMixin() function        dest[key] = deepCopy(src[key], _visited, _copiesVisited);    }    return dest;}

This function is part of my simpleOO library; any bug fixes or enhancements will be made there (feel free to open an issue on github if you discover some bug).