Arc Forumnew | comments | leaders | submitlogin
1 point by rocketnia 4184 days ago | link | parent

If all you want to do is pass arbitrary values into some evaluated code, Function() works for that, and it doesn't use the local scope:

  var foo = (function () {
      var n = {};
      return function ( s ) {
          return Function( "n",
              "\"use strict\";\n" +
              "return (\n" +
              s + "\n" +
              ");\n" +
              "//@ sourceURL=foo"
          )( n );
      };
  })();
  
  foo( "n.foo = 5" );
  foo( "n.foo + 10" );
Technically this implementation accepts a different segment of JavaScript syntax than yours does, but I doubt you care about that in particular.

It's nice that JavaScript provides a way to evaluate code in a local scope, but so far I haven't had much excuse to do that. Occasionally, I do insert an eval( "" ) just to force a closure to capture every single variable in its surrounding lexical scope, since that makes it possible to interact with all those variables when paused there in the Chrome Debugger.



2 points by Pauan 4184 days ago | link

Yes, I tried that but I found it to be significantly slower than using eval. It also requires you to use "return" if you want to actually return the value, whereas eval returns it automatically.

-----