As a part of my template engine I need to be able to evaluate expressions in JavaScript like:
"first || second"
in context of some object serving role of global namespace. So properties of the object should be seen 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 with it and I am able to run it as:
var scope = { first:1, second:2 };
var expr1 = "first || second";
alert( scopedEval(expr1,scope) );
it alerts me 1
.
The only problem with variables that were not defined in the scope object. This:
var expr2 = "third || first || second";
alert( scopedEval(expr2,scope) );
generates an error "variable third
is not defined". But I would like all unknown variables to be resolved to undefined
rather than throwing errors. So "third || first || second" should yield to 1
again.
As for my knowledge such thing is not possible in modern JavaScript but I might miss something so asking. Any ideas?
Here is an example to play with: http://jsfiddle.net/nCCgT/