why do we need self referential object in javascript. example
let a = {};
a.self = a;
now a property self is referring to itself and become circular object.
in nodejs when we use routing library like hapi. the request object which we receive is circular
EDIT: I understood this question to ask "why are circular references allowed in JavaScript".
In general, I'd say an object having itself as a value of its property ( a.self = a
) is not very useful. If you have the reference to the object to take its property, you already have the reference to the object.
However, if the self-reference is deeper, then it makes a lot of sense. For example, trees that allow navigation up:
let tree = { children: [], parent: null };
tree.children.push({ children: [], parent: tree });
Here, tree.children[0].parent === tree
. You have a circular object, but it serves a clear purpose: you can traverse the tree both downwards (via children
) and upwards (via parent
).
We don't.
Ask this code author why they did it. – zerkms
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.