Skip to content

Instantly share code, notes, and snippets.

@n9986
Created January 1, 2014 17:06
Show Gist options
  • Save n9986/8209594 to your computer and use it in GitHub Desktop.
Save n9986/8209594 to your computer and use it in GitHub Desktop.
A possible way to prevent circular references in Javascript using closure.
function A(b) {
this.notSoFunky = 100;
this.setB(b);
}
A.prototype = {
setB: function(b) {
this.B = function() {
return b;
};
}
}
function C(b) {
this.B = b;
}
function B() {
this.funky = 5;
}
B.prototype = {
setA: function(a) {
this.A = a;
},
setC: function(c) {
this.C = c;
}
}
bb = new B();
// cc = new C(bb);
// bb.setC(cc);
aa = new A();
aa.setB(bb);
bb.setA(aa);
// console.log(cc); // UGLY CIRCULAR REFERENCE!!!
console.log(aa);
console.log(aa.B());
console.log(bb);
// Check change propagation
bb.funky = 10;
console.log(aa.B());
console.log(bb);
aa.notSoFunky = 50;
console.log(aa.B().A);
console.log(bb.A);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment