Trouble using 'eval' to define a toplevel function when called from within an object.

Posted by mschaef on Stack Overflow See other posts from Stack Overflow or by mschaef
Published on 2010-06-08T16:19:51Z Indexed on 2010/06/08 16:22 UTC
Read the original article Hit count: 181

Filed under:

I've written (in JavaScript) an interactive read-eval-print-loop that is encapsulated within an object. However, I recently noticed that toplevel function definitions specified to the interpreter do not appear to be 'remembered' by the interpreter. After some diagnostic work, I've reduced the core problem to this:

   var evaler = {
     eval: function (str)
     {
       return eval(str);
     },
   };

   eval("function t1() { return 1; }");         // GOOD
   evaler.eval("function t2() { return 2; }");  // FAIL

After running this script, I have a definition for t1, and no defintion for t2. The act of calling eval from within evaler is sufficiently different from the toplevel call that the global definition does not get recorded. What does happen is that the call to evaler.eval returns a function object, so I'm presuming that t2 is being defined and stored in some other set of bindings that I don't have access to. (It's not defined as a member in evaler.)

Is there any easy fix for this? I've tried all sorts of fixes, and haven't stumbled upon one that works. (Most of what I've done has centered around putting the call to eval in an anonymous function, and altering the way that's called, chainging __parent__, etc.)

Any thoughts on how to fix this?

© Stack Overflow or respective owner

Related posts about JavaScript