JavaScript -- eval function only in certain context with certain "global" variables

0

EDIT: accidentally posted on super user stack exchange, bu tintended to post in on stack overflow... can a moderator move it?

I'm trying to make a function that will evaluate another function (taken as function.toString() or just as a string of the function itself), but only in its own context, with its own set of global variables, which don't exist in any other context, similar to Node.js's runInContext method which allows you to eval certain code along with an object like:

{
    foo: bar
}

and then in the JavaScript string code that is being evaluated you can simply access the variable foo, since it has already been declared as "global" within that scope of the function, and the "global" variable "foo" doesn't exist in any other context.

Is there a way to do something similar like this in client side JavaScript? For example, given the functions:

function hi() {
    console.log(foo + 6);
}

function customEval(func, obj) {
    someKindOfMagicalEvalFunction(func.toString(), obj);
}

Then I should be able to call:

customEval(hi,  {
            foo:8
        })//prints the number "10" to the console

This can / should work similar to the nodejs javascirpt compiler, or even like the JLint library for C#, except written in, and for, client side JavaScript.

bluejayke

Posted 2019-08-26T01:39:22.483

Reputation: 283

No answers