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

23
[deleted]•

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.

1
blatyo•

This would be cool if it worked by adding looking glass after the object is created. However, since it has to exist on instantiation inside the scope of the constructor to see the "private" values, it isn't much use for already existing code.

1
lulzitsaredditOP•

Yes, that would be cool, but impossible -- we need something to share the same context with the private members in order to get our 'foot in the 'door.' As of now, to test private members you would have to either expose those members manually, or put your testing code inside the same context. I think this is a slightly more convenient solution since you only need to put a small function inside.

1