I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s
Shog9♦'s Answer is great. But if your code is just an expression, the code will be executed and nothing will be returned. For expressions, use
function evalInContext(context, js) {
return eval('with(context) { ' + js + ' }');
}
Here is how to use it:
var obj = {key: true};
evalInContext(obj, 'key ? "YES" : "NO"');
It will return "YES".
If you are not sure if the code to be executed is expressions or statements, you can combine them:
function evalInContext(context, js) {
var value;
try {
// for expressions
value = eval('with(context) { ' + js + ' }');
} catch (e) {
if (e instanceof SyntaxError) {
try {
// for statements
value = (new Function('with(this) { ' + js + ' }')).call(context);
} catch (e) {}
}
}
return value;
}