As part of my template engine, I need to evaluate expressions in JavaScript, for example:
"first || second"in the context of some role that serves as the global namespace. Thus, the properties of an object should be considered as global variables.
So far, I came up with this function:
function scopedEval(str, scope) {
var f = new Function("scope", "with(scope) { return (" + str + "); }");
return f(scope);
}
Everything is fine and I can run it as:
var scope = { first:1, second:2 };
var expr1 = "first || second";
alert( scopedEval(expr1,scope) );
he alerts me 1.
The only problem with variables that were not defined in the scope object. It:
var expr2 = "third || first || second";
alert( scopedEval(expr2,scope) );
generates a "variable thirdnot defined" error . But I would like all unknown variables to be resolved before undefined, rather than throwing errors. So, "third || first || second" should again go back to 1.
, JavaScript, - . ?
: http://jsfiddle.net/nCCgT/