25

I have a Model that will "carry" (Model.validator) a validator instance with it, and I need the Validator to have access to the Model's attributes. So, what I have come up with is the following

var Validator = function(model) {
    this.model = model;
};

var Model = function() {
    this._attributes = {};
    this.validator = new Validator(this);
};

var model = new Model();

This code creates a circular reference between those 2 objects. Is this a bad practice that will cause memory leaks? Any other ideas on how to implement it?

P.S. I have seen such circular references between objects in Angular.js scopes.

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Knorcedger
  • 253
  • 3
  • 4
  • 6
    @ArunPJohny: in IE6 maybe... but modern JS engines are perfectly able to handle gc cycles. – georg May 02 '13 at 09:30
  • 3
    @ArunPJohny: Not even in IE6, if they are plain JS objects and do not include the DOM – Bergi May 02 '13 at 09:34
  • 1
    Note that circular references will cause issues when it comes to serialization (through `JSON.stringify()` for example) – Uriel Sep 17 '17 at 15:32

3 Answers3

21

This kind of code will not cause memory leaks with today's browsers; as mentioned on MDN all major browsers have been shipping with mark-and-sweep GCs (that can handle cycles just fine) for some time now (e.g. Firefox itself has had a cycle collector since version 3).

From an architectural standpoint, this kind of code introduces moderately tight coupling between the two objects (if one changes in even a minor way, the other needs to be reviewed to determine if it needs to change as well) and should consequently be avoided if possible. But there is nothing inherently wrong with it.

brettinternet
  • 546
  • 7
  • 21
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 6
    "moderately tight coupling" - you have a gift for understatement. – Erick Robertson May 02 '13 at 12:26
  • 1
    @ErickRobertson: Well, in other languages there is also class-based inheritance, `friend`, "just get the job done dammit" reflection... at least here you can only muck around with the public interface. :-) – Jon May 02 '13 at 12:31
3

It will not be a problem for garbage collection: any new Garbage Collector (>IE6) will handle circular references just fine!

It might be a problem though if you are doing recursive functions, or printing the object.

So the answer is: it is no problem unless you screw up yourselves :-)

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
2

There will not be any problems I'm sure. The most browsers' JS parsers can work with cycle dependecnies while garbage collecting. No more potential issues here.

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153