jQuery.extend() not giving deep copy of object formed by constructor
Posted
by two7s_clash
on Stack Overflow
See other posts from Stack Overflow
or by two7s_clash
Published on 2010-04-28T16:09:00Z
Indexed on
2010/04/28
16:13 UTC
Read the original article
Hit count: 301
I'm trying to use this to clone a complicated Object. The object in question has a property that is an array of other Objects, and each of these have properties of different types, mostly primitives, but a couple further Objects and Arrays.
For example, an ellipsed version of what I am trying to clone:
var asset = new Assets();
function Assets() {
this.values = [];
this.sectionObj = Section;
this.names = getNames;
this.titles = getTitles;
this.properties = getProperties;
...
this.add = addAsset;
function AssetObj(assetValues) {
this.name = "";
this.title = "";
this.interface = "";
...
this.protected = false;
this.standaloneProtected = true;
...
this.chaptersFree = [];
this.chaptersUnavailable = [];
...
this.mediaOptions = {
videoWidth: "",
videoHeight: "",
downloadMedia: true,
downloadMediaExt: "zip"
...
}
this.chaptersAvailable = [];
if (typeof assetValues == "undefined") {
return;
}
for (var name in assetValues) {
if (typeof assetValues[name] == "undefined") {
this[name] = "";
} else {
this[name] = assetValues[name];
}
}
...
function Asset() {
return new AssetObj();
}
...
function getProperties() {
var propertiesArray = new Array();
for (var property in this.values[0]) {
propertiesArray.push(property);
}
return propertiesArray;
}
...
function addAsset(assetValues) {
var newValues;
newValues = new AssetObj(assetValues);
this.values.push(newValues);
}
}
When I do var copiedAssets = $.extend(true, {}, assets);
copiedAssets.values == [], while assets.values == [Object { name="section_intro", more...}, Object { name="select_textbook", more...}, Object { name="quiz", more...}, 11 more...]
When I do var copiedAssets = $.extend( {}, assets);
all copiedAssets.values.[X].properties are just pointers to the value in assets.
What I want is a true deep copy all the way down. What am I missing? Do I need to write a custom extend function? If so, any recommended patterns?
© Stack Overflow or respective owner