Created
January 1, 2014 17:06
-
-
Save n9986/8209594 to your computer and use it in GitHub Desktop.
A possible way to prevent circular references in Javascript using closure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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