3

It's just something I encountered on my journey to learning Javascript and making an application simultaneously.

var A = function (parent) {
    this.parent = parent;
},
    b = new Object();

b.a = new A(b);

This very simple piece of code produces something rather interesting.

console.log(b.a.parent.a.parent.a);

http://i.imgur.com/g6fw6mZ.png Does this cause any problems? Because I am planning on using something similar in my application.

The reason I would use this is because I need to reference a variable belonging to the parent.

It's almost the same problem as here. However, I can't use a closure here, since I don't even have an outermost function!

A stripped down version of my code is as follows:

var Scratchpad = function (canvas) {
    var ctx = canvas.getContext('2d');
    ctx.childMustAccessThis = 3;

    ctx.Brush = new Brush(ctx);
    return ctx;
},
    Brush = function (parent) {
        this.parent = parent;

        // Other vars
    };

Brush.prototype.getContext = function () {
    return this.parent.childMustAccesThis;
}

I need to be making multiple of these Scratchpads (modified context objects) with their respective Brushes.

I'm not sure what to make out of this, it seems harmless but I got a feeling that it's bad practice.

I've tried some other things, such as the closure described in the linked SO post. But of course, that didn't work since my Scratchpad function does not return itself but instead it returns a modified ctx object, so any closure variables are garbage collected (right? they're gone at least).

The rest of my tries relied on wrong understandings of how Javascript objects behave, so those aren't worth mentioning.

So, what should I do with this? Keep it as it is right now? Or do you have any suggestions for a better way of handling this?

Community
  • 1
  • 1
Azeirah
  • 6,176
  • 6
  • 25
  • 44

3 Answers3

3

That's called a circular reference.

Modern garbage collectors (as opposed to Netscape 2.0) will handle it perfectly fine.

Note that older versions of IE cannot handle circular references between DOM objects and pure JS objects.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

There aren't any issues with circular references in modern browsers.

However you need to be aware of them or at least have a mechanism in place to detect them when implementing recursive algorithms. Also, by default JSON.stringify will complain about circular references, but that can easily be dealt with.

Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90
0

There will be no problem using circular references Objects as long as you never need to convert them to JSON!

Clearly recursive Object structures cannot be represented very easily as a String and you will see an error something like this;

TypeError: Converting circular structure to JSON
Jivings
  • 22,834
  • 6
  • 60
  • 101