Alternative to Mozilla's eval in a scope

Andy Chu andy at
Sun Dec 13 21:49:36 PST 2009

I'm writing a JavaScript program ("server-side") that loads plugins
written in JS.  I would like to prevent the plugins from messing with
my program, and from Googling around I found this:

So basically Firefox briefly had a second "scope" argument to eval,
until it became clear that it broke some isolation that people were
expecting, so it was removed.

Is anything like this being discussed for Harmony?  I didn't see
anything in ES5 that addresses this, and I think the original
motivation was good.

How about something like this instead:

There is a function called "loadCode" for now, that behaves a little
bit like eval:

var code = loadCode("var foo=3; var bar = function(a) { fn(a) };",
{fn: obj.fn});

// code is now {foo: 3, bar: function(a) ...}

So the second argument is an object that lists all the names
available.  The return value is an object of names that were defined
in the string.

Since obj.fn.a was not accessible in the original context, fn.a is not
available in the loadCode'd context.

This is much like Python's eval("a=3", {"__builtins__": {}, "json":
json}), except in JS eval() executes statements.  And note in Python
you can control __builtins__, which contains the equivalent of things
like Array, Object, etc.

I've been writing code against Narwhal, which implement CommonJS
modules.  Narwhal uses a nice trick to execute modules in namespaces,
but there's still no getting around the fact that "foo = 3;"
(forgetting the "var") creates a global.  I know ES5 strict mode
addressed this, but it would be nice to also have a loadCode() that
prevents this even for non-strict code.

With most JS engines (v8, Rhino) I think this is fairly easily to
implement, as they all have some notion of execution contexts.  But it
would be nice to have an engine-dependent way of doing it, by having
it in JS itself.  Also I think this is fairly similar to what's
required to implement web workers.

I just started reading the group and haven't been able to find any
related discussion e.g. here:


More information about the es-discuss mailing list