0

Why does the code below create and infinitely deep object? I'm assuming its something with const and scope. How can I prevent this?

const DEFAULT_PROP = {children: []}
class Class {
  constructor(prop = {}) {
    assignProperties(this, prop, DEFAULT_PROP);
  }
}

//Loops props in the default and if they are given use them, if not use fallback
function assignProperties(element, given, defaults) {
    for (let property in defaults) {
        if (property in given) {
            element[property] = given[property];
        } else {
            element[property] = defaults[property];
        }
    }
}

var parent = new Class();

parent.children.push(new Class());

console.log(parent);

I've looked at this and it seems that when I change Class.children I'm actually change the DEFAULT_PROP.children too so that I'm just referencing itself. How can I avoid this?

According to this I should be using Object.assign() to create a unlinked clone to then copy from, but my implementation did not work. (See below)

const DEFAULT_PROP = {children: []}
class Class {
  constructor(prop = {}) {
    assignProperties(this, prop, DEFAULT_PROP);
  }
}

//Loops props in the default and if they are given use them, if not use fallback
function assignProperties(element, given, defaults) {
    let defaultsClone = Object.assign({}, defaults);

    for (let property in defaultsClone) {
        if (property in given) {
            element[property] = given[property];
        } else {
            element[property] = defaultsClone[property];
        }
    }
}

var parent = new Class();

parent.children.push(new Class());

console.log(parent);

What did I do wrong?

Jack
  • 1,893
  • 1
  • 11
  • 28
  • What you're doing in your code is a shallow copy. `children` still is connected to `DEFAULT_PROPS` attribute. You need to do a deep copy. See this question; a comment under the first answer mentions this issue: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – kaveh Dec 04 '20 at 21:19
  • So its sounds like I'm supposed to use `eval()`, but what I have complex data? – Jack Dec 04 '20 at 21:27

0 Answers0