Mar 7, 2010

shadow copy in jQuery

We can use jQuery to copy(clone) an object to a new object, so the old object and the new object can evolved independently.


//shadow copy object
var oldObj = { name: "fred" };
var newObj = jQuery.extend({}, oldObj);
newObj.name = "jeff";
alert(oldObj.name); //fred


To do similar thing for array, we can use [].slice() method


//clone array
var newArray = arr.slice(0);