Ryan Ryan - 23 days ago 6
Javascript Question

How to eval variables into local scope object's properties instead of global scope in JavaScript

I have some code return from server like "var myVar = 314;", I would like to create a context object like so var context = {}; and then eval the script "var myVar = 314;" into properties of context, how could I achieve this ?

I have tried the below code, but without success:

var context = {};
eval.call(context, "var myVar = 314;");


EDIT
May be I wasn't clear enough in the first place, the result I expected is: after eval(), I got the properties in the context object, the aim is to avoid global scope population.

For example,

var context = {};
eval.call(context, "var myVar = 314;");


I would expect the result as context.myVar = 314.

Answer

Are you able to change the format of the script you get from your server? If so, follow the advice in Aadit's comment and have your server send:

context["myVar"] = 314;

or:

context.myVar = 314;

If you can't change the format, is the script literally as simple as var myVar = 314;?

If it is, try rethinking the approach. Instead of trying to eval() the script in some particular context, parse the script into a form you can work with. For example:

var script = 'var myVar = -314.5;';  // what we get from the server
var match = script.match( /var\s+(\w+)\s*=\s*(-?[\d.]+)\s*;/ );
if( match ) {
    // match[1] is 'myVar', match[2] is '-314.5'
    context[ match[1] ] = +match[2];
}
console.log( context );

Now context is { myVar: -314.5 }. This code could be run inside a function or anywhere and would work the same.

You could use a similar regular expression for a string variable assignment:

var script = 'var myString = "Test Value";';  // what we get from the server
var match = script.match( /var\s+(\w+)\s*=\s*"([^"]*)"\s*;/ );
if( match ) {
    // match[1] is 'myString', match[2] is 'Test Value'
    context[ match[1] ] = match[2];
}
console.log( context );

This time, context is { myString: "Test Value" }

This approach could easily be adapted for multiple variables, other data types, etc.