- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Articles
- Why circular reference is bad in javascript?
- How and why to avoid global variables in JavaScript?
- OOP Terminology in Python
- How to avoid inserting NULL values to a table with JavaScript?
- Avoid Unexpected string concatenation in JavaScript?
- How to avoid jQuery function conflict with any other JavaScript library
- How to avoid “StaleElementReferenceException” in Selenium?
- How to avoid childhood Obesity?
- How to Avoid Online Scams?
- What are Python OOP Basics?
- Difference between OOP and POP
- How to avoid printing newline in Python?
- How to avoid bugs in cloud computing
- How to Avoid Errors in Java Code?
- Circular linked lists in Javascript
