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);
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?