The Looking Glass: Inspecting closure based private members with eval.
Hey guys. Some patterns use closures to simulate private members as you would find in some other languages. Unfortunately, Javascript does not provide any way to access these members for testing and debugging (AFAIK). Luckily, we can work around this weakness by using eval.
// Should also work with the Module Pattern
var singleton = new (function () {
var a = 342;
var privFunc = function (a,b) { return a+b; };
this.lookingGlass = function (fn) {
return eval("("+fn+")()");
}
});
singleton.lookingGlass(function () {
test("a private member", function() {
equals(a, 342, "a == 342");
});
console.log(a == 342);
//etc.
});
Whether there is a need to test a private members is another issue, as is whether there is a need for member privacy in the first place. This is just a work around, i.e., a hack, for this apparent limitation. What do you guys think?
Posted Aug 13, 2010, 6:13 PM UTC
Very clever, actually. I consider this property of closures to be a feature rather than a limitation, but it's true that debugging it is annoying. This is a neat technique.