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?

4

3 回答 3

3

这称为循环引用。

现代垃圾收集器(与 Netscape 2.0 不同)可以很好地处理它。

请注意,旧版本的 IE 无法处理 DOM 对象和纯 JS 对象之间的循环引用。

于 2013-09-24T17:25:10.767 回答
1

现代浏览器中的循环引用没有任何问题。

但是,您需要了解它们,或者至少有一种机制来在实现递归算法时检测它们。此外,默认情况下JSON.stringify会抱怨循环引用,但这很容易处理

于 2013-09-24T17:30:42.213 回答
0

只要您永远不需要将它们转换为 JSON,使用循环引用对象就没有问题!

显然递归对象结构不能很容易地表示为字符串,您将看到类似这样的错误;

TypeError: Converting circular structure to JSON
于 2013-09-24T17:25:44.173 回答