sleepless_in_seattle
sleepless_in_seattle

Reputation: 2224

Referring to parent object from the child

class Test {
    constructor() {
        this.childObject = new Child();
    }

    parentHello() {
        console.log("Parent Hello World!");
    }
}

class Child {
    childHello() {
        // How do I call parentHello() from here?
    }
}
const obj = new Test();
obj.childObject.childHello();

I'm trying to call the parentHello() from the childHello(). The only way I came up with is to change the structure to circular like this:

class Test {
    constructor() {
        this.childObject = new Child(this);
    }

    parentHello() {
        console.log("Parent Hello World!");
    }
}

class Child {
    constructor(parent) {
        this.parent = parent;
    }

    childHello() {
        this.parent.parentHello();
    }
}
const obj = new Test();
obj.childObject.childHello();

But after doing this I'm no longer able to convert it to JSON. Is there a proper way to do this?

EDIT: I also tried super() but it only works when extending.

Upvotes: 0

Views: 56

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18409

Your solution with reference to parent via constructor is ok I think. To allow serialization to JSON, you can use second parameter of JSON.stringify (replacer):

A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.

class Test {
    constructor() {
        this.childObject = new Child(this);
    }

    parentHello() {
        console.log("Parent Hello World!");
    }
}

class Child {
    constructor(parent) {
        this.parent = parent;
    }

    childHello() {
        this.parent.parentHello();
    }
}
const obj = new Test();

var cache = [];
var json = JSON.stringify(obj, (key, value) => {
    if (typeof value === 'object' && value !== null) {
        if (cache.includes(value)) {
            return;
        }

        cache.push(value);
    }

    return value;
});

console.log(json);

Upvotes: 1

Related Questions