gpt4 book ai didi

javascript - 从子对象引用父对象

转载 作者:行者123 更新时间:2023-12-03 03:09:39 25 4
gpt4 key购买 nike

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();

我正在尝试从 childHello() 调用parentHello()。我想出的唯一方法是将结构更改为圆形,如下所示:

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();

但是这样做之后我无法再将其转换为 JSON。有没有正确的方法来做到这一点?

编辑:我也尝试过 super() 但它仅在扩展时有效。

最佳答案

我认为您通过构造函数引用父级的解决方案是可以的。要允许序列化为 JSON,您可以使用 JSON.stringify (替换器)的第二个参数:

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);

关于javascript - 从子对象引用父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com