简体   繁体   English

父子关系和对象查看器中的导航

[英]parent-child relationships and navigating in object viewer

Is it a problem that when I view a parent-child relationship written in JavaScript you can infinitely navigate through the object? 当我查看用JavaScript编写的父子关系时,您可以无限地浏览对象吗?

Take the following as an example 以以下为例

class Parent {
    constructor() {
      this.child = null;
    }
}

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

let p1 = new Parent();
let c1 = new Child();

p1.child = c1;
c1.parent = p1;

When viewing this object in Chrome when navigating the object you can iterate it infinitely, which is obvious why but is it bad practice is there another way to code parent / child relationships in JavaScript? 在Chrome浏览器中浏览该对象时,您可以对其进行无限迭代,这很显然是为什么,但是不好的实践是,还有另一种方法可以用JavaScript编写父/子关系吗?

在此处输入图片说明

child -> parent -> child -> parent -> child -> parent -> child -> and so on ... 孩子->父母->孩子->父母->孩子->父母->孩子->等等...

This is a natural effect of objects being passed by reference, rather than by value. 这是对象通过引用而不是通过值传递的自然效果

 const x = { a: 'INITIAL', b: 'INITIAL', } const y = { x, cloneX: { ...x } } console.log(y) xa = 'CHANGED' console.log(y) 

From looking at the question, and your comments, it sounds as though this is unlikely to be particularly new to you. 通过查看问题和您的评论,听起来好像这对您来说并不是特别新鲜。

But what we can tell from knowing that the variable is passed by reference is that what you're seeing in the console is fairly natural once you consider that the parent/child values are just pointers, so naturally you'll be able to keep following them. 但是,我们可以知道变量是通过引用传递的,因此,一旦您认为父/子值只是指针,您在控制台中看到的内容就很自然了,因此您自然可以继续关注他们。

This doesn't imply however that there will be any kind of memory issue, as the code isn't keeping an infinite series of copies of objects; 但是,这并不意味着会存在任何类型的内存问题,因为代码不会保留对象的无限数量的副本。 each only stores a reference, it just happens in this case to be circular. 每个都只存储一个引用,在这种情况下它只是循环的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM