The jQuery extend method allows you to simply copy the properties of an object from one to another.
Here is a contrived but illustrative example. It even shows why you don't need βdeepβ copy features!
var someObj = { a : "a", b : 12345, c : { d : "d", e : "e" }, f : function() { alert(this.a); } }; //copy from original to new empty object var deepCopy = $.extend(true, {}, someObj); deepCopy.a = "deepCopy.a"; deepCopy.cd = "deepCopy.cd"; alert("someObj is not affected when deep copying: " + someObj.cd); alert("deepCopy is entirely distinct when deep copying: " + deepCopy.cd); deepCopy.f(); someObj.f();
Here is the fiddle for your convenience: http://jsfiddle.net/S6p3F/3/
Running this code, you will see that someObj and deepCopy identical in structure, but to separate objects.
As you can see, deep copying of functions is not required, since the this link is tied to any object to which the function applies. This is because in javascript, calling the deepCopy.f() function is functionally equivalent to deepCopy.f.call(deepCopy) . A more illustrative example:
function someFunction() { alert(this.someProperty); } var a = { someProperty: "a property" }, b = { someProperty: "b property" }; someFunction.call(a); someFunction.call(b);
And the fiddle: http://jsfiddle.net/S6p3F/2/
Wickyilliams
source share