How to avoid circular reference in OOP Javascript?


A circular reference occurs if two separate objects pass references to each other.

In older browsers circular references were a cause of memory leaks. With improvements in Garbage collection algorithms, which can now handle cycles and cyclic dependencies fine, this is no longer an issue.

However, from a pure design point of view, circular referencing is still a bad thing and a code smell. Circular referencing implies that the 2 objects referencing each other are tightly coupled and changes to one object may need changes in other as well.

Avoiding circular references

There is no one way to avoid circular reference in JS. It depends on the use case and the situation and may also be necessary in some cases. We can take an example to understand this:

Suppose you have 2 objects, Dog and Person. You want to be able to reference the owner of a dog just using the dog object and the pet of a person using the person object.

let dog = new Dog();
let person = new Person();
// Creating a circular reference
dog.owner = person
person.pet = dog

In most scenarios you'll need to access only one object and derive the other from it. so you can break one of the links. If not then you can use a map to map objects in the reverse scenario. But instead of using hacks, it is better to let the circular ref be there.

Updated on: 17-Sep-2019

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements